﻿using DevExpress.Entity.ProjectModel;
using DevExpress.Mvvm;
using DevExpress.Mvvm.Native;
using DevExpress.Xpf.Core;
using DevExpress.XtraPrinting;
using HandyControl.Controls;
using ImTools;
using log4net;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using PlaceOrder_Core.Helper;
using PlaceOrder_Core.Models.QuanYi;
using PlaceOrder_Core.PlaceOrderModels;
using PlaceOrder_Core.Services.Instances;
using PlaceOrder_Core.Services.Interfaces;
using PlaceOrder_Core.Services.Wechat;
using PlaceOrder_Server.Events;
using PlaceOrder_Server.Helper;
using PlaceOrder_Shared.Models.Common;
using PlaceOrder_Shared.Models.Daily;
using PlaceOrder_Shared.Models.Trade;
using Prism.Commands;
using Prism.DryIoc;
using Prism.Events;
using Prism.Mvvm;
using System.Collections.Concurrent;
using System.Collections.ObjectModel;
using System.Globalization;
using System.IO;
using System.Net.Http;
using System.Net.WebSockets;
using System.Runtime.InteropServices;
using System.Text;
using System.Timers;
using System.Windows.Threading;
using WebSocketSharp;
using WindowsInput;
using WindowsInput.Native;
using BindableBase = Prism.Mvvm.BindableBase;
using DelegateCommand = Prism.Commands.DelegateCommand;
namespace PlaceOrder_Server.ViewModels
{
    public class IndexServerViewModel : BindableBase
    {
        private readonly ILog _log;
        private readonly IDailyData _dailyData;
        private readonly IUserHelper _userHelper;
        private ServerWebSocketHelper serverWebSocketFromClient;
        private ServerWebSocketHelper serverWebSocketFromAdmin;
        private ClientWebSocketHelper clientWebSocketToLily;
        private static List<ChatReceiver> Receivers = new List<ChatReceiver>();
        private int CurrentDailyID = 0;
        private bool AdminIsConnected = false; //是否连接到管理端

        public DelegateCommand TestCommand { get; set; }
        public DelegateCommand TestCommand2 { get; set; }
        public DelegateCommand TestCatchCommand { get; set; }
        public DelegateCommand ClearMessageCommand { get; set; }
        public DelegateCommand SendQTradeNotOpenCommand{ get; set; }

        private readonly IEventAggregator _eventAggregator;
        //ILog log, IDailyData dailyData, IEventAggregator eventAggregator, IUserHelper userHelper
        public IndexServerViewModel(ILog log, IDailyData dailyData, IEventAggregator eventAggregator, IUserHelper userHelper)
        {


            _eventAggregator = eventAggregator;
            _log = log;
            _dailyData = dailyData;
            _userHelper = userHelper;
            Receivers = _dailyData.GetChatReceivers();
            RegisterHotKey();//快捷键关闭服务
            this.BrokerList = Receivers.Select(o => o.ChatId).Distinct().ToList();
            UserData = _dailyData.GetAllUsers().ToObservableCollection();
            InitValue();
            InitChatName();
            InitCommand();
            ClearAllChatMessage();
            Thread lilyServiceThread = new Thread(ConnectLiuService); //对接刘老师接口
            lilyServiceThread.Start();


            Thread normalServiceThread = new Thread(StartNormalServerService); //服务端（接收客户端消息）38888端口
            normalServiceThread.Start();

            // 启动处理消息队列的任务
            _ = ProcessQuanYiServerMessageQueueAsync();
            Thread adminServiceThread = new Thread(StartAdminServerService); //服务端（接收管理端消息）38889端口
            adminServiceThread.Start();



            //StartCaptureMessageService();
            Thread captureThread = new Thread(StartCaptureMessageService);//捕获消息服务
            captureThread.Start();


            SetupDailyStopTimer(); //每日9.50分停止抓取

            TestCommand = new DelegateCommand(() =>
            {

                //this.Websocket_LilyInformEvent("1");
                this.ModifyInterval();

                //this.SendTestMessageToLily();
            });

            // 模拟程序启动时立即开始监听心跳
            StartListeningForHeartbeat();
        }

        private System.Timers.Timer heartbeatTimer;
        private bool heartbeatReceived;
        /// <summary>
        /// 监听心跳，如果心跳超过45秒还是没收到就重连
        /// </summary>
        /// <exception cref="NotImplementedException"></exception>
        private void StartListeningForHeartbeat()
        {
            // 初始化定时器
            heartbeatTimer = new System.Timers.Timer(45000); // 45秒
            heartbeatTimer.Elapsed += OnHeartbeatTimeout;
            heartbeatTimer.AutoReset = true; // 自动重置
            heartbeatTimer.Start();
        }

        private void OnHeartbeatTimeout(object sender, ElapsedEventArgs e)
        {
            try
            {
                if (!heartbeatReceived)
                {
                    AppLog.WriteError("35秒内未收到心跳，执行重连...");
                    //ClientWebSocketToLily_LilyDisconnectEvent();
                    AppLog.WriteError("执行ClientWebSocketToLily_LilyDisconnectEvent方法...");

                }
                heartbeatReceived = false; // 重置心跳接收标志
            }
            catch(Exception ex)
            {
                AppLog.WriteError("OnHeartbeatTimeout异常"+ex.Message);
            }
         
        }

        private int heartCount = 0;
        private void OnHeartbeatReceived()
        {
            AppLog.WriteWarn($"收到pong心跳包{++heartCount}次");
            heartbeatReceived = true;
        }
        private static System.Timers.Timer stopTimer;
        private void SetupDailyStopTimer()
        {
            // 计算到达目标时间的时间间隔
            DateTime now = DateTime.Now;
            DateTime nextStopTime = DateTime.Today.AddHours(21).AddMinutes(50); // 21:50
            //DateTime nextStopTime = DateTime.Today.AddHours(16).AddMinutes(16); // 21:50

            if (now > nextStopTime)
            {
                nextStopTime = nextStopTime.AddDays(1); // 如果已经过了目标时间，设置为明天的目标时间
            }

            TimeSpan timeUntilNextStop = nextStopTime - now;

            stopTimer = new System.Timers.Timer(timeUntilNextStop.TotalMilliseconds);
            stopTimer.Elapsed += (o, a) =>
            {
                // 停止主定时器
                StopTimer();
                PrismApplication.Current.Dispatcher.Invoke(() =>
                {
                    string clipboardStr = Clipboard.GetText();
                    AppLog.WriteInfo($"清空剪贴板前,数据为{clipboardStr}");

                    Clipboard.Clear();
                    clipboardStr = Clipboard.GetText();
                    AppLog.WriteInfo($"清空剪贴板后,数据为{clipboardStr}");
                });

               


                Thread.Sleep(5000);


                ClearAllChatMessage();
                Thread.Sleep(2000);

                AppLog.WriteInfo("程序关闭了！");
                PrismApplication.Current.Dispatcher.Invoke(() =>
                {
                    PrismApplication.Current.Shutdown();
                });

            };
            stopTimer.AutoReset = false; // 只执行一次
            stopTimer.Start();
        }

        /// <summary>
        /// 聊天记录清屏
        /// </summary>
        private void ClearAllChatMessage()
        {
            try
            {

                foreach (var chatName in ChatName)
                {
                    ClearChatMessageFromWindow(chatName);
                }
            }
            catch (Exception ex)
            {
                AppLog.WriteError("ClearAllChatMessage清屏异常" + ex.Message + ex.StackTrace);
            }
            finally
            {
                //semaphore.Release();
            }
        }
        private void ClearChatMessageFromWindow(string chatterName)
        {
            try
            {
                lock (lockObject)
                {
                    IntPtr hWnd = Helper.WindowHelper.FindWindow(null, chatterName);
                    if (hWnd == IntPtr.Zero)
                    {
                        hWnd = Helper.WindowHelper.FindWindow(null, Helper.WindowHelper.getAnotherTitle(chatterName));
                        if (hWnd == IntPtr.Zero)
                        {
                            //AppLog.WriteWarn($"未找到{chatterName}的窗口");
                            return; // Window not found
                        }
                    }
                    else
                    {

                        PrismApplication.Current.Dispatcher.Invoke(() =>
                        {
                            ShowWindow(hWnd, SW_SHOWNORMAL);
                            Thread.Sleep(20);
                            SetForegroundWindow(hWnd);
                            Thread.Sleep(10);
                            //SendKeys.SendWait("{ENTER}");
                        });

                        // 异步获取窗口左上角坐标
                        Point windowPoint = Helper.WindowHelper.GetWindowTopLeftCorner("QiDian", chatterName);

                        if (windowPoint.X == 0 && windowPoint.Y == 0 || windowPoint.X.ToString().Contains("-32000"))
                        {
                            AppLog.WriteInfo($"窗体 {chatterName} 在原点（0,0）");
                            return;
                            // 窗体在原点（0,0）
                        }
                        IntPtr handleQD = Helper.WindowHelper.WindowFromPoint(windowPoint);
                        ClearChatWindow(windowPoint, handleQD, chatterName);
                    }
                }

            }
            catch (System.Exception ex)
            {
                AppLog.WriteError($"{ex.Message}--{ex.StackTrace}, CheckMsgFromWindow for {chatterName}");
            }
        }



        /// <summary>
        /// 窗口抖动
        /// </summary>
        /// <param name="chatterName"></param>
        private void WindowShaking(string chatterName)
        {
            try
            {
                lock (lockObject)
                {
                    IntPtr hWnd = Helper.WindowHelper.FindWindow(null, chatterName);
                    if (hWnd == IntPtr.Zero)
                    {
                        hWnd = Helper.WindowHelper.FindWindow(null, Helper.WindowHelper.getAnotherTitle(chatterName));
                        if (hWnd == IntPtr.Zero)
                        {
                            //AppLog.WriteWarn($"未找到{chatterName}的窗口");
                            return; // Window not found
                        }
                    }
                    else
                    {

                        PrismApplication.Current.Dispatcher.Invoke(() =>
                        {
                            ShowWindow(hWnd, SW_SHOWNORMAL);
                            Thread.Sleep(20);
                            SetForegroundWindow(hWnd);
                            Thread.Sleep(10);
                            //SendKeys.SendWait("{ENTER}");
                        });

                        // 异步获取窗口左上角坐标
                        Point windowPoint = Helper.WindowHelper.GetWindowTopLeftCorner("QiDian", chatterName);

                        if (windowPoint.X == 0 && windowPoint.Y == 0 || windowPoint.X.ToString().Contains("-32000"))
                        {
                            AppLog.WriteInfo($"窗体 {chatterName} 在原点（0,0）");
                            return;
                            // 窗体在原点（0,0）
                        }
                        IntPtr handleQD = Helper.WindowHelper.WindowFromPoint(windowPoint);
                        ShakeChatWindow(windowPoint, handleQD, chatterName);
                    }
                }

            }
            catch (System.Exception ex)
            {
                AppLog.WriteError($"{ex.Message}--{ex.StackTrace}, CheckMsgFromWindow for {chatterName}");
            }
        }
        private int leftDistance=60;

        public int LeftDistance
        {
            get { return leftDistance; }
            set { leftDistance = value;RaisePropertyChanged(); }
        }
        private int topDistance=95;

        public int TopDistance
        {
            get { return topDistance; }
            set { topDistance = value; RaisePropertyChanged(); }
        }

        private int shakeTopDistance=385;

        public int ShakeTopDistance
        {
            get { return shakeTopDistance; }
            set { shakeTopDistance = value; RaisePropertyChanged(); }
        }

        private int shakeLeftDistance = 215;

        public int ShakeLeftDistance
        {
            get { return shakeLeftDistance; }
            set { shakeLeftDistance = value; RaisePropertyChanged(); }
        }



        public int ClearTopDistance = 365;
        public int ClearLeftDistance = 330;
        public int ClearDown = 95;
        public int ClearLeft = 120;
        private string ClearChatWindow(Point windowPoint, IntPtr hwnd, string chatName)
        {
            try
            {
                //AppLog.WriteInfo($"{chatName}--窗体左上角为：x:{windowPoint.X},y:{windowPoint.Y}！");

                //模拟 右键 点击 然后 清屏
                //int down1 = 350;
                lock (lockObject)
                {

                    string clipboardContent = null;

                    int sendMessageCount = 0;
                    int receiveMessageCount = 0;
                    int searchStartX = windowPoint.X + ClearLeftDistance; // 发送方起始搜索点的 X 坐标
                    int searchStartY = windowPoint.Y + ClearTopDistance; // 发送方起始搜索点的 Y 坐标
             
                    var sim = new InputSimulator();
                    // 将屏幕坐标转换为虚拟桌面坐标
                    int virtualScreenX = searchStartX * 65535 / Screen.PrimaryScreen.Bounds.Width;
                    int virtualScreenY = searchStartY * 65535 / Screen.PrimaryScreen.Bounds.Height;

                    // 模拟右键点击打开menu
                    sim.Mouse.MoveMouseToPositionOnVirtualDesktop(virtualScreenX, virtualScreenY);
                    sim.Mouse.RightButtonClick();

                    // 等待点击操作完成
                    Thread.Sleep(100);

                    // 向下移动50像素
                    virtualScreenY += ClearDown * 65535 / Screen.PrimaryScreen.Bounds.Height;
                    sim.Mouse.MoveMouseToPositionOnVirtualDesktop(virtualScreenX, virtualScreenY);

                    // 向右移动50像素
                    virtualScreenX += ClearLeft * 65535 / Screen.PrimaryScreen.Bounds.Width;
                    sim.Mouse.MoveMouseToPositionOnVirtualDesktop(virtualScreenX, virtualScreenY);
                    Thread.Sleep(100);
                    // 左键点击模拟清屏操作
                    sim.Mouse.LeftButtonClick();
                    // 等待复制操作完成
                 

                    // 再次点击取消焦点
                    //sim.Mouse.LeftButtonClick();
                    //Thread.Sleep(200);

                    Thread staThread = new Thread(
                                   delegate ()
                                   {
                                       try
                                       {
                                           // 确保线程在 STA 模式下运行
                                           if (Thread.CurrentThread.GetApartmentState() != ApartmentState.STA)
                                           {
                                               AppLog.WriteError("必须要是STA线程执行啊!");
                                               throw new ThreadStateException("The thread must be in STA mode to access the clipboard.");

                                           }

                                           //// 获取剪贴板的文本内容
                                           //clipboardContent = Clipboard.GetText();
                                           //var ParsedMessage = ParseMessages(clipboardContent);

                                           //if (!AllChatDictionary.ContainsKey(chatName))
                                           //{

                                           //    UpdateMessages(chatName, ParsedMessage);
                                           //}
                                           //else
                                           //{
                                           //    UpdateMessages(chatName, ParsedMessage);
                                           //}
                                       }

                                       catch (Exception ex)
                                       {

                                       }
                                   });
                    staThread.SetApartmentState(ApartmentState.STA);
                    staThread.Start();
                    staThread.Join();
                }




                AppLog.WriteInfo("聊天人" + chatName + "清屏");





                return "1";
            }
            catch (Exception ex)
            {
                AppLog.WriteError("聊天人" + chatName + ex.Message + "清屏异常");
            }
            finally
            {

            }
            return null;
        }

        private string ShakeChatWindow(Point windowPoint, IntPtr hwnd, string chatName)
        {
            try
            {
                //AppLog.WriteInfo($"{chatName}--窗体左上角为：x:{windowPoint.X},y:{windowPoint.Y}！");

                //模拟 右键 点击 然后 清屏

                lock (lockObject)
                {

                    string clipboardContent = null;

                    int sendMessageCount = 0;
                    int receiveMessageCount = 0;
                    int searchStartX = windowPoint.X; // 发送方起始搜索点的 X 坐标
                    int searchStartY = windowPoint.Y; // 发送方起始搜索点的 Y 坐标

                    var sim = new InputSimulator();
                    // 将屏幕坐标转换为虚拟桌面坐标
                    int virtualScreenX = searchStartX * 65535 / Screen.PrimaryScreen.Bounds.Width;
                    int virtualScreenY = searchStartY * 65535 / Screen.PrimaryScreen.Bounds.Height;

                   
                    

                   
                    sim.Mouse.MoveMouseToPositionOnVirtualDesktop(virtualScreenX, virtualScreenY);

                    virtualScreenY += ShakeTopDistance * 65535 / Screen.PrimaryScreen.Bounds.Height;
                    virtualScreenX += ShakeLeftDistance * 65535 / Screen.PrimaryScreen.Bounds.Width;
                    //Thread.Sleep(2000);
                    sim.Mouse.MoveMouseToPositionOnVirtualDesktop(virtualScreenX, virtualScreenY);
                    Thread.Sleep(20);

                    AppLog.WriteInfo($"发送窗口抖动！目标中介：{chatName}");
                    ChatMessageLog+= ($"发送窗口抖动！目标中介：{chatName}");
                    sim.Mouse.LeftButtonClick();
               
                }









                return "1";
            }
            catch (Exception ex)
            {
                AppLog.WriteError("聊天人" + chatName + ex.Message + "抓取文本异常");
            }
            finally
            {

            }
            return null;
        }
        private void InitChatName()
        {
            try
            {
                this.ChatName = _dailyData.GetChatReceivers().Select(o => o.Target.Trim()).Distinct().ToList();
            }
            catch(Exception ex)
            {
                AppLog.WriteError("InitChatName异常" + ex.StackTrace + "," + ex.Message);
            }
          
        }

        private void SendTestMessageToLily()
        {
            var chatMsg = new ChatMessage() { BrokerId = 2, ChatId = 107, TradeId = 5049, ChatMessageInfo = "T002 bid 240210 2.384 7月9日+0 2k", CreateTime = DateTime.Now };

            this.SaveMessageToLily(0, chatMsg);

        }
        #region 我的服务端连接刘老师服务端（接收推送）
        private System.Timers.Timer reconnectLilyTimer;
        private bool isReconnectingLily = false; // 标记是否正在重连，用于避免重复触发重连操作
        private void ConnectLiuService()
        {
            try
            {
                clientWebSocketToLily = new ClientWebSocketHelper();
                clientWebSocketToLily.LilyInformEvent -= Websocket_LilyInformEvent;

                clientWebSocketToLily.LilyDisconnectEvent -= ClientWebSocketToLily_LilyDisconnectEvent;
                clientWebSocketToLily.LilyInformEvent += Websocket_LilyInformEvent;

                clientWebSocketToLily.LilyDisconnectEvent += ClientWebSocketToLily_LilyDisconnectEvent;
                clientWebSocketToLily.SubscribeLilyServerData(1);
            }
            catch (Exception ex)
            {
                AppLog.WriteError("ConnectLiuService 异常" + ex.StackTrace + ex.Message);
            }
        }
        public bool isLilyReconnecting = false;
        private void ClientWebSocketToLily_LilyDisconnectEvent()
        {

            try
            {
                AppLog.WriteError("服务端和lily断连");
                if (isLilyReconnecting)
                    return;
                // 设置正在重连标志
                isLilyReconnecting = true;
                // 可以在这里添加重连逻辑
                // 检查是否正在重连，避免重复触发
                if (reconnectLilyTimer != null)
                {
                    // 停止定时器
                    reconnectLilyTimer.Stop();

                    // 解除事件处理程序
                    reconnectLilyTimer.Elapsed -= TryReconnect;

                    // 释放资源
                    reconnectLilyTimer.Dispose();

                    // 设为 null
                    reconnectLilyTimer = null;
                    AppLog.WriteError("reconnectLilyTimer置空");
                }
                else
                {
                    AppLog.WriteError("重新开启lily重连定时器");
                    StartReconnectLilyTimer();
                }
       
                
            }
            catch (Exception ex)
            {
                AppLog.WriteError("ClientWebSocketToLily_LilyDisconnectEvent" + ex.Message + ex.StackTrace);
            }
        }

        private readonly object reconnectLock = new object();
        private void StartReconnectLilyTimer()
        {
            reconnectLilyTimer = new System.Timers.Timer();
            reconnectLilyTimer.Interval = 3000; // 设置重连间隔为3秒
            reconnectLilyTimer.Elapsed -= TryReconnect;

            reconnectLilyTimer.Elapsed += TryReconnect;
            reconnectLilyTimer.AutoReset = true; // 设置为true，确保定时器重复执行

            // 启动定时器
            reconnectLilyTimer.Start();
        }

        private async void TryReconnect(object? sender, ElapsedEventArgs e)
        {
            
                try
                {
                    bool success = await clientWebSocketToLily.SubscribeLilyServerData(1);
                    if (success)
                    {
                        AppLog.WriteInfo("TryReconnect--重新连接至Lily成功！！");
                        reconnectLilyTimer?.Stop(); // Stop() 更加明确地停止定时器
                        reconnectLilyTimer = null;
                        isLilyReconnecting = false;
                    }
                  
                    //// 防止并发重连
                    //if (isReconnectingLily)
                    //{
                    //    return;
                    //}

                    //isReconnectingLily = true;

                    //// 在重新连接之前进行一些清理操作
                    //if (clientWebSocketToLily != null && clientWebSocketToLily.clientWebSocket.ReadyState == WebSocketState.Open)
                    //{
                    //    clientWebSocketToLily.Dispose(); // 关闭当前的 WebSocket 连接
                    //}

                    //// 重新创建新的 ClientWebSocketHelper 实例
                    //clientWebSocketToLily = new ClientWebSocketHelper();
                    //clientWebSocketToLily.LilyInformEvent += Websocket_LilyInformEvent;
                    //clientWebSocketToLily.LilyDisconnectEvent += ClientWebSocketToLily_LilyDisconnectEvent;

                    //// 连接到 Lily 服务器
                    //clientWebSocketToLily.SubscribeLilyServerData(1); // 这里需要实现 Connect 方法来连接到 WebSocket 服务器

                    //// 重连成功后重置标志
                    //isReconnectingLily = false;
                    //AppLog.WriteInfo("重新连接到 Lily 服务器成功");
                    //AppLog.WriteFatal("重新连接到 Lily 服务器成功");
                }
                catch (Exception ex)
                {
                    AppLog.WriteError($"重连失败: {ex.Message}");
                    reconnectLilyTimer?.Stop();
                    reconnectLilyTimer?.Dispose();
                    StartReconnectLilyTimer();
                    // 可以选择在此处添加重试逻辑，例如延时后再次尝试重连
                }
                finally
                {
                    //isReconnectingLily = false;
                }
            
        }

        private void TryReconnect(object test)
        {

            //try
            //{
            //    // 在重新连接之前可以进行一些清理操作
            //    clientWebSocketToLily?.Dispose(); // 关闭当前的 WebSocket 连接，如果有的话

            //    // 重新创建新的 ClientWebSocketHelper 实例
            //    clientWebSocketToLily = new ClientWebSocketHelper();
            //    //clientWebSocketToLily.SubscribeLilyServerData();
            //    clientWebSocketToLily.LilyInformEvent += Websocket_LilyInformEvent;
            //    clientWebSocketToLily.LilyDisconnectEvent += ClientWebSocketToLily_LilyDisconnectEvent;

            //    // 连接到 Lily 服务器
            //    clientWebSocketToLily.SubscribeLilyServerData(1); // 这里需要实现 Connect 方法来连接到 WebSocket 服务器

            //    Thread.Sleep(1000);
            //    // 重连成功后重置标志
            //    isReconnectingLily = false;
            //    AppLog.WriteInfo("重新连接到 Lily 服务器成功");
            //    AppLog.WriteFatal("重新连接到 Lily 服务器成功");
            //}
            //catch (Exception ex)
            //{
            //    AppLog.WriteError($"重连失败: {ex.Message}");
            //    StartReconnectLilyTimer();
            //    // 可以选择在此处添加重试逻辑，例如延时后再次尝试重连
            //}
        }


        // 全局定义一个集合用于存储已处理的消息
        //private static HashSet<string> processedQiangPingMessages = new HashSet<string>();
        private ConcurrentDictionary<string, bool> processedQiangPingMessages = new ConcurrentDictionary<string, bool>();
        private static string GenerateUniqueKey(string userID, string brokerId, string tradeId, string messageSend)
        {
            return $"{userID}_{brokerId}_{tradeId}_{messageSend}";
        }


        private readonly ConcurrentQueue<string> messageQueue = new ConcurrentQueue<string>();
        private readonly SemaphoreSlim semaphore2 = new SemaphoreSlim(1, 1);
        private void Websocket_LilyInformEvent(string Message)
        {
            AppLog.WriteInfo($"收到lily消息---{Message}");
            messageQueue.Enqueue(Message);
            ProcessQueueAsync();
            //Task.Run(() => ProcessMessageAsync(Message));
        }

        private async Task ProcessQueueAsync()
        {
            await semaphore2.WaitAsync();
            try
            {
                while (messageQueue.TryDequeue(out var message))
                {
                    await ProcessMessageAsync(message);
                }
            }
            finally
            {
                semaphore2.Release();
            }
        }

        private async Task ProcessMessageAsync(string Message)
        {
            try
            {
                // 解析 JSON 数据
                JObject jsonMessage = JObject.Parse(Message);

                // 提取信息
                string dataKey = jsonMessage["dataKey"]?.ToString();
                string dataType = jsonMessage["dataType"]?.ToString();
                //AppLog.WriteError("ProcessMessageAsync收到数据" + dataKey + dataType);
                AppLog.WriteWarn("处理Lily---ProcessMessageAsync内容" + jsonMessage.ToString());
                switch (dataType)
                {
                    case "pong":
                        OnHeartbeatReceived(); // 调用收到心跳包的处理方法
                        return;

                    case "tradeamountlimit":
                        return;

                    case "qiangping":
                        AppLog.WriteWarn("收到lily的qiangping！");
                        await HandleQiangPingMessage(jsonMessage);
                        break;
                    case "send":
                        AppLog.WriteWarn("收到lily的send！");
                       
                        await HandleShenHeSendMessage(jsonMessage);
                        break;
                    case "chat_message":
                    case "accept_bond_1":
                    case "accept_bond_0":
                    case "deal_bond_0":
                    case "deal_bond_1":
                    case "request_cancel_bond_0":
                    case "request_cancel_bond_1":
                    case "confirm_cancel_bond_0":
                    case "confirm_cancel_bond_1":
                    case "deny_cancel_bond_0":
                    case "deny_cancel_bond_1":
                    case "xiugaichangedeny_bond_0":
                    case "xiugaichangedeny_bond_1":
                    case "usertradechange_bond_0":
                    case "usertradechange_bond_1":
                        return;

                    case "xunjiachangerequest_bond_1":
                    case "xunjiachangerequest_bond_0":
                        //string info1 = LilyMessageConverterHelper.ConvertToRealMessage(dataType);
                        //Growl.InfoGlobal($"系统收到改价消息 —— {info1}");
                        //SearchHandle();
                        break;

                    default:
                        AppLog.WriteWarn("lily -indexserverViewmodel 其余消息" + Message);
                        //this.WebSocketInfo = "lily -orderlistviewmodel 其余消息" + Message;
                        // SearchHandle();
                        break;
                }
            }
            catch (Exception ex)
            {
                AppLog.WriteError("收到强平异常Websocket_InformEvent" + ex.Message + ex.StackTrace);
            }
        }

        #region 临时类
        public class RootFromLily
        {
            public string? DataKey { get; set; }
            public string? DataType { get; set; }
            public string? ActionType { get; set; }
            public ChatDataFromLily? Data { get; set; }
        }

        public class ChatDataFromLily
        {
            public string Id { get; set; }
            public int ChatId { get; set; }
            public string ChatMessage { get; set; }
            public int BrokerId { get; set; }
            public int Direction { get; set; }
            public CreateTimeFromLily CreateTime { get; set; }
            public string? TradeId { get; set; }
            public object IsTrade { get; set; }
            public CreateTimeFromLily UpdateTime { get; set; }
            public object QuoteMessage { get; set; }
            public string ChannelId { get; set; }
            public string BrokerName { get; set; } // 添加 BrokerName 字段
        }

        public class CreateTimeFromLily
        {
            public int Year { get; set; }
            public int MonthValue { get; set; }
            public int DayOfMonth { get; set; }
            public int Hour { get; set; }
            public int Minute { get; set; }
            public int Second { get; set; }
            public int Nano { get; set; }
        }
        #endregion

         private async void TestMethod()
        {
            var jsonData = new
            {
                dataKey = (string)null,
                dataType = "send",
                actionType = "popup",
                data = new
                {
                    id = "10b5e5b9e3d5446f8274491e4cd84b6d",
                    chatId = 1,
                    chatMessage = "我是测试管理员\n",
                    brokerId = 1,
                    direction = 0,
                    creaTime = new
                    {
                        year = 2024,
                        monthValue = 9,
                        hour = 17,
                        minute = 53,
                        second = 38,
                        nano = 734000000,
                        dayOfYear = 249,
                        dayOfWeek = "THURSDAY",
                        month = "SEPTEMBER",
                        dayOfMonth = 5,
                        chronology = new
                        {
                            calendarType = "iso8601",
                            id = "ISO"
                        }
                    }
                },
                tradeId = (string)null,
                isTrade = (string)null,
                updateTime = new
                {
                    year = 2024,
                    monthValue = 9,
                    hour = 17,
                    minute = 53,
                    second = 38,
                    nano = 734000000,
                    dayOfYear = 249,
                    dayOfWeek = "THURSDAY",
                    month = "SEPTEMBER",
                    dayOfMonth = 5,
                    chronology = new
                    {
                        calendarType = "iso8601",
                        id = "ISO"
                    }
                },
                quoteMessage = (string)null,
                channelId = "f09639756a47415fb4fbf6d31febba4"
            };

            // 解析 JSON 数据
            // 将对象序列化为JSON字符串
            string jsonString = JsonConvert.SerializeObject(jsonData, Formatting.Indented);

            // 使用JObject解析JSON字符串
            JObject jsonMessage = JObject.Parse(jsonString);
            await HandleShenHeSendMessage(jsonMessage); // 使用异步方法
        }

        // 存储审核员发送的消息Ids
        private static readonly HashSet<string> sendIds = new HashSet<string>();
        private async Task HandleShenHeSendMessage(JObject jsonMessage)
        {
            try
            {
                RootFromLily root = jsonMessage.ToObject<RootFromLily>();
                ChatDataFromLily item = root.Data;

                List<ChatMessage> newMessages = new List<ChatMessage>();
                string id = item.Id;
                // Check if the ID has already been processed
                if (sendIds.Contains(id))
                {
                    AppLog.WriteError("有相同的Send-ID" + id);
                    // If ID is already processed, skip further handling
                    return;
                }
                AppLog.WriteError("增加审核消息ID：" + id);

                // Add the new ID to the set
                sendIds.Add(id);
                int direction = item.Direction;
                int brokerId = item.BrokerId;
                string chatMsg = item.ChatMessage;
                int chatId = item.ChatId;
             
                string tradeId = item.TradeId;
                // 获取中介名称
                string brokerName = Receivers.Where(o => o.Brokerid == item.BrokerId).FirstOrDefault()?.Company;

                // 生成消息信息
                string chatInfo = $"消息内容：{item.ChatMessage}\r\n" +
                                  $"时间：{DateTime.Now}\r\n" +
                                  $"中介：{brokerName}";

                var message = new QuanYiOrderServerResponseClass { DataType = QuanYiServerBaseClass.DataTypeEnum.ChatMessage, ChatMessage = chatMsg, BrokerID = brokerId, UserID = chatId };
                if (message != null && SendMessage(message, 2))
                {
                    string msg = $"记录审核消息，中介：{brokerName},发起人ChatId：{chatId},消息内容：{chatMsg} \r\n";
                    AppLog.WriteInfo(msg);
                    PrismApplication.Current.Dispatcher.Invoke(() => { this.ChatMessageLog += msg; });
                   
                    //clientWebSocketToLily.ReplyToLily("11111");
                }
            }
            catch(Exception ex)
            {
                AppLog.WriteError("HandleShenHeSendMessage异常" + ex.Message);
            }
            
            
        }

        private async Task HandleQiangPingMessage(JObject jsonMessage)
        {
            var data = jsonMessage["data"];

            string userID = data["yanjiuyuanId"]?.ToString();
            string brokerId = data["brokerID"]?.ToString();
            string messageSend = data["message"]?.ToString();
            string tradeId = data["userTradeID"]?.ToString();

            string uniqueKey = GenerateUniqueKey(userID, brokerId, tradeId, messageSend);
            AppLog.WriteInfo("收到lily的强平消息: " + jsonMessage);
            if (!processedQiangPingMessages.TryAdd(uniqueKey, true))
            {
                AppLog.WriteError("重复消息，舍弃: " + uniqueKey);
                return;
            }

            QuanYiOrderServerResponseClass qsr = new QuanYiOrderServerResponseClass
            {
                Trade = new UserTrade
                {
                    ChatID = userID,
                    UserTradeID = Convert.ToInt64(tradeId),
                    BrokerID = int.Parse(brokerId)
                }
            };

            if (Receivers == null)
            {
                Receivers = _dailyData.GetChatReceivers();
            }

            qsr.Trade.ChannelID = Receivers.FirstOrDefault(o => o.Brokerid == int.Parse(brokerId))?.ChannelId;
            qsr.Message = messageSend;

            // 询价单发送给lily
            if (qsr != null && SendMessage(qsr, 1))
            {
                ChatMessage chatMessage = new ChatMessage
                {
                    BrokerId = qsr.Trade.BrokerID,
                    ChannelId = qsr.Trade.ChannelID,
                    ChatMessageInfo = qsr.Message,
                    TradeId = qsr.Trade.UserTradeID,
                    ChatId = int.Parse(qsr.Trade.ChatID)
                };
                ChatMessageLog+= ($"发送强平单！！给lily,brokerId={chatMessage.BrokerId},channelId={chatMessage.ChannelId},消息={chatMessage.ChatMessageInfo},TradeId={chatMessage.TradeId},ChatID={chatMessage.ChatId}");
                AppLog.WriteInfo($"发送强平单！！给lily,brokerId={chatMessage.BrokerId},channelId={chatMessage.ChannelId},消息={chatMessage.ChatMessageInfo},TradeId={chatMessage.TradeId},ChatID={chatMessage.ChatId}");
                this.SaveMessageToLily(0, chatMessage);
            }
        }

        //private void Websocket_LilyInformEvent(string Message)
        //{
        //    try
        //    {
        //        // 解析 JSON 数据
        //        JObject jsonMessage = JObject.Parse(Message);

        //        // 提取信息
        //        string dataKey = jsonMessage["dataKey"]?.ToString();
        //        string dataType = jsonMessage["dataType"]?.ToString();
        //        //AppLog.WriteFatal("lily -服务端 所有消息" + Message);

        //        switch (dataType)
        //        {
        //            case "pong":
        //                AppLog.WriteFatal("收到心跳包" + dataKey + dataType);
        //                return;
        //                break;
        //            #region 丢弃不做处理的
        //            case "tradeamountlimit":
        //                return;
        //                break;
        //            #endregion


        //            //发送撤单/改价指令给中介

        //            case "qiangping":
        //                var data = jsonMessage["data"];

        //                string userID = data["yanjiuyuanId"]?.ToString();
        //                string brokerId = data["brokerID"]?.ToString();
        //                string messageSend = data["message"]?.ToString();
        //                string tradeId = data["userTradeID"]?.ToString();

        //                string uniqueKey = GenerateUniqueKey(userID, brokerId, tradeId, messageSend);

        //                if (!processedQiangPingMessages.TryAdd(uniqueKey, true))
        //                {
        //                    AppLog.WriteFatal("重复消息，舍弃: " + uniqueKey);
        //                    return;
        //                }

        //                QuanYiOrderServerResponseClass qsr = new QuanYiOrderServerResponseClass
        //                {
        //                    Trade = new UserTrade
        //                    {
        //                        ChatID = userID,
        //                        UserTradeID = Convert.ToInt64(tradeId),
        //                        BrokerID = int.Parse(brokerId)
        //                    }
        //                };

        //                if (Receivers == null)
        //                {
        //                    Receivers = _dailyData.GetChatReceivers();
        //                }

        //                qsr.Trade.ChannelID = Receivers.FirstOrDefault(o => o.Brokerid == int.Parse(brokerId))?.ChannelId;
        //                qsr.Message = messageSend;

        //                // 询价单发送给lily
        //                if (qsr != null && SendMessage(qsr, 1))
        //                {
        //                    ChatMessage chatMessage = new ChatMessage
        //                    {
        //                        BrokerId = qsr.Trade.BrokerID,
        //                        ChannelId = qsr.Trade.ChannelID,
        //                        ChatMessageInfo = qsr.Message,
        //                        TradeId = qsr.Trade.UserTradeID,
        //                        ChatId = int.Parse(qsr.Trade.ChatID)
        //                    };

        //                    AppLog.WriteFatal($"发送强平单！！给lily,brokerId={chatMessage.BrokerId},channelId={chatMessage.ChannelId},消息={chatMessage.ChatMessageInfo},TradeId={chatMessage.TradeId},ChatID={chatMessage.ChatId}");
        //                    this.SaveMessageToLily(0, chatMessage);
        //                }

        //                break;
        //            //case "qiangping":

        //            //    var data = jsonMessage["data"];

        //            //    string userID = data["yanjiuyuanId"]?.ToString();
        //            //    string brokerId = data["brokerID"]?.ToString();
        //            //    string messageSend = data["message"]?.ToString();
        //            //    string tradeId = data["userTradeID"]?.ToString();

        //            //    string uniqueKey = GenerateUniqueKey(userID, brokerId, tradeId, messageSend);
        //            //    QuanYiOrderServerResponseClass qsr = new QuanYiOrderServerResponseClass();
        //            //    if (processedQiangPingMessages.Contains(uniqueKey))
        //            //    {
        //            //        AppLog.WriteFatal("重复消息，舍弃: " + uniqueKey);
        //            //        return;
        //            //    }

        //            //    processedQiangPingMessages.Add(uniqueKey);

        //            //    qsr.Trade = new UserTrade();
        //            //    qsr.Trade.ChatID = userID;

        //            //    if (Receivers == null)
        //            //    {
        //            //        Receivers = _dailyData.GetChatReceivers();
        //            //    }
        //            //    qsr.Trade.ChannelID = Receivers.Where(o => o.Brokerid == int.Parse(brokerId)).FirstOrDefault().ChannelId;
        //            //    qsr.Trade.UserTradeID = Convert.ToInt64(tradeId);
        //            //    qsr.Trade.BrokerID = int.Parse(brokerId);
        //            //    qsr.Message = messageSend;



        //            //    //询价单发送给lily
        //            //    if (qsr != null)
        //            //    {
        //            //        if (SendMessage(qsr, 1))
        //            //        {
        //            //            ChatMessage chatMessage = new ChatMessage() { BrokerId = qsr.Trade.BrokerID, ChannelId = qsr.Trade.ChannelID, ChatMessageInfo = qsr.Message, TradeId = qsr.Trade.UserTradeID, ChatId = int.Parse(qsr.Trade.ChatID) };
        //            //            AppLog.WriteFatal($"发送强平单！！给lily,brokerId={chatMessage.BrokerId},channelId={chatMessage.ChannelId},消息={chatMessage.ChatMessageInfo},TradeId={chatMessage.TradeId},ChatID={chatMessage.ChatId}");
        //            //            this.SaveMessageToLily(0, chatMessage);
        //            //        }


        //            //    }
        //            //    break;


        //            //case "chat_message":
        //            //    // 创建一个唯一标识符（例如组合时间戳和消息内容）
        //            //    // 格式化 createTime 为 "yyyy-MM-dd HH:mm:ss"
        //            //    RootFromLily root = jsonMessage.ToObject<RootFromLily>();
        //            //    ChatDataFromLily item = root.Data;
        //            //    string formattedCreateTime = new DateTime(item.CreateTime.Year, item.CreateTime.MonthValue, item.CreateTime.DayOfMonth, item.CreateTime.Hour, item.CreateTime.Minute, item.CreateTime.Second)
        //            //                                 .ToString("yyyy-MM-dd HH:mm:ss");
        //            //    List<ChatMessage> newMessages = new List<ChatMessage>();


        //            //    this.WebSocketInfo += "聊天消息" + item.ChatMessage + "\r\n";
        //            //    int direction = item.Direction;
        //            //    int brokerId = item.BrokerId;
        //            //    string chatMsg = item.ChatMessage;
        //            //    int chatId = item.ChatId;
        //            //    string tradeId = item.TradeId;
        //            //    //string brokerName = item.BrokerName;
        //            //    // 将字符串转换为 DateTime 类型
        //            //    DateTime createTime;
        //            //    if (DateTime.TryParse(formattedCreateTime, out createTime))
        //            //    {
        //            //        // 转换成功
        //            //        // Console.WriteLine(createTime);
        //            //    }
        //            //    else
        //            //    {
        //            //        // 转换失败，处理错误
        //            //        AppLog.WriteError("转换错误");
        //            //        Console.WriteLine("Invalid date format");
        //            //    }

        //            //    // 创建一个唯一标识符（例如组合时间戳和消息内容）
        //            //    string uniqueIdentifier = $"{formattedCreateTime}_{item.ChatMessage}";

        //            //    // 检查是否已经处理过该消息
        //            //    if (!processedMessages.Contains(uniqueIdentifier))
        //            //    {
        //            //        // 获取中介名称
        //            //        string brokerName = ChatReceivers.Where(o => o.Brokerid == item.BrokerId).FirstOrDefault()?.Company;

        //            //        // 生成消息信息
        //            //        string chatInfo = $"消息内容：{item.ChatMessage}\r\n" +
        //            //                          $"时间：{formattedCreateTime}\r\n" +
        //            //                          $"中介：{brokerName}";
        //            //        Growl.InfoGlobal($"收到一条新消息：{chatInfo}");

        //            //        // 添加到已处理集合中
        //            //        processedMessages.Add(uniqueIdentifier);
        //            //        long parsedTradeId = 0;
        //            //        if (!string.IsNullOrEmpty(tradeId) && !long.TryParse(tradeId, out parsedTradeId))
        //            //        {
        //            //            parsedTradeId = 0;
        //            //        }
        //            //        var chatMsgModel = new ChatMessage() { Direction = (short?)direction, ChatMessageInfo = chatMsg, CreateTime = createTime, BrokerId = brokerId, BrokerName = brokerName ?? "未知", ChatId = chatId, TradeId = parsedTradeId };
        //            //        newMessages.Add(chatMsgModel);
        //            //    }
        //            //    //string brokerName = ChatReceivers.Where(o=>o.Brokerid==item.BrokerId).FirstOrDefault().Company;
        //            //    //string chatinfo = $"消息内容：{item.ChatMessageInfo}\r\n" +
        //            //    //    $"时间：{item.CreateTime}\r\n" +
        //            //    //    $"中介：{brokerName}";
        //            //    //item.BrokerName = brokerName;
        //            //    //Growl.InfoGlobal($"收到一条新消息：{chatinfo}");


        //            //    // 仅对新的消息列表进行发送
        //            //    if (newMessages.Count > 0)
        //            //    {
        //            //        //Messenger.Default.Send(newMessages, MessageToken.NewChatMessageIn);
        //            //        Messenger.Default.Send(newMessages, MessageToken.SendChatMessage);
        //            //        if (newMessages[0].Direction == 1)
        //            //        {
        //            //            SearchHandle();
        //            //        }
        //            //    }
        //            //    break;
        //            case "chat_message":
        //            case "accept_bond_1":
        //            case "accept_bond_0":
        //            case "deal_bond_0":
        //            case "deal_bond_1":
        //            case "request_cancel_bond_0":
        //            case "request_cancel_bond_1":
        //            case "confirm_cancel_bond_0":
        //            case "confirm_cancel_bond_1":
        //            case "deny_cancel_bond_0":
        //            case "deny_cancel_bond_1":
        //            case "xiugaichangedeny_bond_0":
        //            case "xiugaichangedeny_bond_1":
        //            case "usertradechange_bond_0":
        //            case "usertradechange_bond_1":
        //                return;
        //                break;

        //            case "xunjiachangerequest_bond_1":
        //            case "xunjiachangerequest_bond_0":
        //                //string info1 = LilyMessageConverterHelper.ConvertToRealMessage(dataType);
        //                //Growl.InfoGlobal($"系统收到改价消息 —— {info1}");
        //                //SearchHandle();
        //                break;
        //            default:
        //                AppLog.WriteFatal("lily -orderlistviewmodel 其余消息" + Message);
        //                //this.WebSocketInfo = "lily -orderlistviewmodel 其余消息" + Message;
        //                // SearchHandle();
        //                break;
        //        }

        //        //OrderListViewModel.ShowQiangPing(qiangPingMessage);

        //    }
        //    catch (Exception ex)
        //    {
        //        AppLog.WriteError("收到强平异常Websocket_InformEvent" + ex.Message + ex.StackTrace);
        //    }
        //}



        private void ClientWebSocketToLily_QiangpingEvent(PlaceOrder_Shared.ModelsToLily.QiangPingOrder qiangPingOrder)
        {
        }

        #endregion

        private void InitCommand()
        {
            ClearChatDataCommand = new DelegateCommand(ClearChatData);
            WindowShakeCommand = new DelegateCommand(ShakeWindow);
            TestCatchCommand = new DelegateCommand(TestCatch);
            CloseWebSocketCommand = new DelegateCommand(() =>
            {
                this.clientWebSocketToLily.UnSubscribeLilyServerData();
            });
            ClearMessageCommand = new DelegateCommand(() =>
            {
                this.ChatMessageLog = null;
            });

            TestCommand2 = new DelegateCommand(() => { this.TestMethod(); });

            SendQTradeNotOpenCommand = new(SendQTradeNotOpen);
        }

        private void ClearChatData()
        {
            //ClearAllChatMessage();
            if (this.SelectedBrokerName == null)
            {
                Growl.ErrorGlobal("未选择中介请检查");
                return;
            }
            if (this.SelectedStartDate == null)
            {
                Growl.ErrorGlobal("请选择时间");
                return;
            }
            ClearChatMessageFromWindow(SelectedBrokerName);
            int brokerId = (int)Receivers.Where(o => o.ChatId == this.SelectedBrokerName).FirstOrDefault().Brokerid;

        }

        /// <summary>
        /// 窗口抖动
        /// </summary>
        private void ShakeWindow()
        {
            if (this.SelectedBrokerName == null)
            {
                Growl.ErrorGlobal("未选择中介请检查");
                return;
            }
            if (this.SelectedStartDate == null)
            {
                Growl.ErrorGlobal("请选择时间");
                return;
            }
            WindowShaking(SelectedBrokerName);
            //int brokerId = (int)Receivers.Where(o => o.ChatId == this.SelectedBrokerName).FirstOrDefault().Brokerid;

        }

        private async void InitValue()
        {
            //Trades = await Task.Run(() => _dailyData.GetUserTrades().ToObservableCollection());

            //PlaceOrder_Core.Services.Instances.DailyData.ChannelId = _dailyData.GetChannelId();
            try
            {
                var tradesNew = await Task.Run(() => UserHelper.FindAllXunJiaOrdersAsync());
                if (tradesNew==null||tradesNew.Count==0)
                {
                    AppLog.WriteWarn("InitValue没有询价单");
                    return;
                }
                var tradeModels = tradesNew.Select(trade => new UserTrade
                {
                    // 根据需要设置 UserTrade 对象的属性
                    // 例如：
                    BrokerID = trade.BrokerId,
                    Status = trade.Status,
                    Price = (decimal)trade.Price,
                    Volume = (int.Parse)(trade.Volume),
                    OnHoldVolume = (int.Parse)(trade.RestVolume),
                    TsCode = trade.Tscode,
                    Time = trade.CreateTime,
                    DealType = trade.Direction == "bond_0" ? "买入" : (trade.Direction == "bond_1" ? "卖出" : "未知"), // 根据Direction设置DealType
                    UserTradeID = trade.UserTradeId,
                    ChannelID = trade.ChannelId,
                    DeliveryDate = DateOnly.FromDateTime(trade.DeliveryTime),
                    DeliverySpeed = trade.DeliverySpeed,
                    Target = trade.Target
                    // 其他属性赋值
                }).ToList();

                PrismApplication.Current.Dispatcher.Invoke(() => { Trades = tradeModels.ToObservableCollection(); });
                Greet();
            }
            catch (Exception ex)
            {
                AppLog.WriteError("InitValue异常" + ex.Message);
            }


        }
        #region 命令
        public DelegateCommand ClearChatDataCommand { get; set; }
        public DelegateCommand WindowShakeCommand { get; set; }
        public DelegateCommand CloseWebSocketCommand { get; set; }
        
        #endregion


        #region 依赖属性

        /// <summary>
        /// 清空的开始时间
        /// </summary>
        private DateTime _selectedStartDate = DateTime.Now;

        public DateTime SelectedStartDate
        {
            get { return _selectedStartDate; }
            set
            {
                _selectedStartDate = value;
                RaisePropertyChanged();
            }
        }
        private string selectedBrokerName;

        public string SelectedBrokerName
        {
            get { return selectedBrokerName; }
            set { selectedBrokerName = value; RaisePropertyChanged(); }
        }


        /// <summary>
        /// 中介列表
        /// </summary>
        private List<string> brokerList;

        public List<string> BrokerList
        {
            get { return brokerList; }
            set { brokerList = value; RaisePropertyChanged(); }
        }


        private ObservableCollection<TradeSimUser> userData;
        public ObservableCollection<TradeSimUser> UserData
        {
            get => userData;
            set
            {
                if (userData != value)
                {
                    userData = value;
                    RaisePropertyChanged();
                }
            }
        }


        private ObservableCollection<UserTrade> trades;
        public ObservableCollection<UserTrade> Trades
        {
            get => trades;
            set
            {
                if (trades != value)
                {
                    trades = value;
                    RaisePropertyChanged();
                }
            }
        }



        /// <summary>
        /// 捕获聊天记录的日志
        /// </summary>
        private string chatMessageLog;

        public string ChatMessageLog
        {
            get { return chatMessageLog; }
            set { chatMessageLog = value; RaisePropertyChanged(); }
        }


        /// <summary>
        /// 下单的日志
        /// </summary>
        private string orderLog;

        public string OrderLog
        {
            get { return orderLog; }
            set { orderLog = value; RaisePropertyChanged(); }
        }

        #endregion


        #region 服务端——对接客户端服务
        public void StartNormalServerService()
        {
            try
            {
                serverWebSocketFromClient = new ServerWebSocketHelper(_dailyData);
                serverWebSocketFromClient.QuanYiOrderServerMessageEvent -= Websocket_QuanYiServerMessageEvent;
                serverWebSocketFromClient.SubscribeLilyTradeEvent -= WebSocketHelper_SubscribeLilyTradeEvent;
                serverWebSocketFromClient.QuanYiOrderServerMessageEvent += Websocket_QuanYiServerMessageEvent;
                serverWebSocketFromClient.SubscribeLilyTradeEvent += WebSocketHelper_SubscribeLilyTradeEvent;
                serverWebSocketFromClient.serverWebSocketStart();
            }
            catch (Exception ex)
            {
                AppLog.WriteError("StartNormalServerService异常" + ex.StackTrace + ex.Message);
            }

        }

        private void WebSocketHelper_SubscribeLilyTradeEvent(LilyTradeModel Trade)
        {
            try
            {
                UserTrade t = Trades.FirstOrDefault(x => x.UserTradeID == int.Parse(Trade.userTradeId));
                if (t != null)
                {
                    int RestVolume = int.Parse(Trade.restVolume);
                    if (RestVolume == 0)
                    {
                        PrismApplication.Current.Dispatcher.Invoke(() =>
                        {
                            Receivers.FirstOrDefault(x => x.Brokerid == t.BrokerID).OrderInProgress = false;

                        });
                    }
                    t.OnHoldVolume = RestVolume;
                }
            }
            catch (Exception ex)
            {
                AppLog.WriteError(ex.Message + "PlaceOrderServer" + "WebSocketHelper_SubscribeLilyTradeEvent" + ex.StackTrace);
            }
        }
        private readonly ConcurrentQueue<QuanYiOrderServerResponseClass> _messageQueue = new ConcurrentQueue<QuanYiOrderServerResponseClass>();

        private int i = 0;
        private async Task ProcessQuanYiServerMessageQueueAsync()
        {
            while (true)
            {
                if (_messageQueue.TryDequeue(out var qsr))
                {
                    AppLog.WriteInfo($"执行{++i}次");
                    await ProcessMessageAsync(qsr);
                }
                await Task.Delay(10); // 避免空循环
            }
        }

        private async Task ProcessMessageAsync(QuanYiOrderServerResponseClass QSR)
        {
            try
            {
                // 异步处理数据
                await Task.Run(() => ProcessMessage(QSR));
            }
            catch (Exception ex)
            {
                AppLog.WriteError("处理消息时发生错误: " + ex.Message);
            }
        }

        public void ProcessMessage(QuanYiOrderServerResponseClass QSR)
        {
            try
            {
                UserTrade tmpTrade;
                TradeSimUser user;
                ChatReceiver chat;
                int result;
                int UserTradeID;
                string msg;
                int ActualVolume;

                AppLog.WriteFatal("收到客户端QSR" + QSR.ToString());
                //var tradesNew =  UserHelper.FindAllXunJiaOrdersAsync().Result;
                //var tradeModels = tradesNew.Select(trade => new UserTrade
                //{
                //    // 根据需要设置 UserTrade 对象的属性
                //    // 例如：
                //    BrokerID = trade.BrokerId,
                //    Status = trade.Status,
                //    Price = (decimal)trade.Price,
                //    Volume = (int.Parse)(trade.Volume),
                //    OnHoldVolume = (int.Parse)(trade.RestVolume),
                //    TsCode = trade.Tscode,
                //    Time = trade.CreateTime,
                //    DealType = trade.Direction == "bond_0" ? "买入" : (trade.Direction == "bond_1" ? "卖出" : "未知"), // 根据Direction设置DealType
                //    UserTradeID = trade.UserTradeId,
                //    ChannelID = trade.ChannelId,
                //    DeliveryDate = DateOnly.FromDateTime(trade.DeliveryTime),
                //    DeliverySpeed = trade.DeliverySpeed,
                //    Target = trade.Target
                //    // 其他属性赋值
                //}).ToList();

                //PrismApplication.Current.Dispatcher.Invoke(() => { Trades = tradeModels.ToObservableCollection(); });
                // 异步获取数据
  
                var tradesNew = UserHelper.FindAllXunJiaOrdersAsync().Result;

                if (tradesNew != null)
                {
                    // 使用并行化处理数据
                    var tradeModels = tradesNew.AsParallel().Select(trade => new UserTrade
                    {
                        BrokerID = trade.BrokerId,
                        Status = trade.Status,
                        Price = (decimal)trade.Price,
                        Volume = int.Parse(trade.Volume),
                        OnHoldVolume = int.Parse(trade.RestVolume),
                        TsCode = trade.Tscode,
                        Time = trade.CreateTime,
                        DealType = trade.Direction == "bond_0" ? "买入" : (trade.Direction == "bond_1" ? "卖出" : "未知"),
                        UserTradeID = trade.UserTradeId,
                        ChannelID = trade.ChannelId,
                        DeliveryDate = DateOnly.FromDateTime(trade.DeliveryTime),
                        DeliverySpeed = trade.DeliverySpeed,
                        Target = trade.Target
                    }).ToList();

                    // 在后台线程更新UI
                    PrismApplication.Current.Dispatcher.Invoke(() =>
                    {
                        Trades = tradeModels.ToObservableCollection();
                    });
                }
                else
                {
                    AppLog.WriteError("未能获取交易数据");
                }
                switch (QSR.DataType)
                {
                    case QuanYiServerBaseClass.DataTypeEnum.Login:
                        string logInMsg = QSR.UserID + "登录了服务端";
                        AppLog.WriteInfo(logInMsg);
                        PrismApplication.Current.Dispatcher.InvokeAsync(() =>
                        {
                            OrderLog += logInMsg+"\r\n";
                        });
                        //user = UserData.Single(x => x.UserID == QSR.UserID);
                        //PrismApplication.Current.Dispatcher.Invoke(() =>
                        //{
                        //    user.Status = 1;
                        //    user.LoginTime = DateTime.Now;
                        //});
                        //QSR.Code = 0;
                        //QSR.Message = "OK";
                        //if (user.UserStatus > SimTradeUserStatusEnmu.Normal)
                        //{
                        //    QSR.Code = 0;
                        //    QSR.Message = ((int)user.UserStatus).ToString();
                        //    QSR.DataType = QuanYiServerBaseClass.DataTypeEnum.UserStatusChange;
                        //    QSR.Trade = new UserTrade();
                        //    QSR.Trade.Time = user.DisabledTime;
                        //}
                        //OrderLog += "登录相关：" + QSR.UserID + "回应：" + QSR.Message + "\r\n";
                        //serverWebSocketFromClient?.SendMessageToAdmin(QSR);
                        break;
                    case QuanYiServerBaseClass.DataTypeEnum.Logout:

                        string logOutMsg = QSR.UserID + "登出了";
                        AppLog.WriteInfo(logOutMsg);
                        PrismApplication.Current.Dispatcher.InvokeAsync(() =>
                        {
                            OrderLog += logOutMsg+"\r\n";
                        });
                       
                        //user = UserData.Single(x => x.UserID == QSR.UserID);
                        //PrismApplication.Current.Dispatcher.Invoke(() =>
                        //{
                        //    user.Status = 0;
                        //    user.LogoutTime = DateTime.Now;
                        //});
                        //OrderLog += "登出相关：" + QSR.UserID + "回应：" + QSR.Message + "\r\n";

                        return;
                    case QuanYiServerBaseClass.DataTypeEnum.Order:
                        try

                        {
                            //tmpTrade = Trades.FirstOrDefault(x => x.Guid == QSR.Trade.Guid);
                            //if (tmpTrade != null)
                            //{
                            //    QSR.Code = 8;
                            //    QSR.Message = "订单已存在";
                            //    QSR.DataType = QuanYiServerBaseClass.DataTypeEnum.Order;
                            //    break;
                            //}

                            //var s = UserData;
                            //if (UserData.Single(x => x.UserID == QSR.UserID).UserStatus > (SimTradeUserStatusEnmu)1)
                            //{
                            //    QSR.Code = 10;
                            //    QSR.Message = "用户已被禁";
                            //    QSR.DataType = QuanYiServerBaseClass.DataTypeEnum.Order;
                            //    break;
                            //}
                            QSR.Trade.Command = "";
                            int? brokerid = QSR.Trade.BrokerID;
                            //if (QSR.Trade.ReceiverId == 0)
                            //{
                            //    brokerid = 0;
                            //    List<BidHistory> AllowedBids = ServerWebSocketHelper.GetBidHistories(QSR.Trade.TsCode);
                            //    AllowedBids = AllowedBids.Where(x => UserData.Single(y => y.UserID == QSR.UserID).BrokerList.Contains(x.BrokerId)).ToList();
                            //    AllowedBids = AllowedBids.Where(x => !Trades.Where(y => y.OnHoldVolume > 0 & y.TsCode == QSR.Trade.TsCode & y.OrderType == QSR.Trade.OrderType).GroupBy(z => z.BrokerID).Select(z => z.Key).Contains(x.BrokerId)).ToList();
                            //    PrismApplication.Current.Dispatcher.Invoke(() =>
                            //    {
                            //        AllowedBids = AllowedBids
                            //            .Where(x => !Trades
                            //                .Where(y => y.OnHoldVolume > 0 && y.TsCode == QSR.Trade.TsCode && y.OrderType == QSR.Trade.OrderType)
                            //                .GroupBy(z => z.BrokerID)
                            //                .Select(z => z.Key)
                            //                .Contains(x.BrokerId))
                            //            .ToList();
                            //    });
                            //    if (AllowedBids.Count == 0)
                            //    {
                            //        List<UserTrade> tmpTrades = null;
                            //        bool bFindSamePrice = false;
                            //        PrismApplication.Current.Dispatcher.Invoke(() =>
                            //        {
                            //            tmpTrades = Trades.Where(x => x.TsCode == QSR.Trade.TsCode & x.OrderType == QSR.Trade.OrderType).OrderBy(x => x.Price).ToList();

                            //        });
                            //        //List<UserTrade> tmpTrades = Trades.Where(x => x.TsCode == QSR.Trade.TsCode & x.OrderType == QSR.Trade.OrderType).OrderBy(x => x.Price).ToList();
                            //        UserTrade t = null;
                            //        if (QSR.Trade.OrderType == UserTrade.UserTradeOrderTypeEnum.Bid)
                            //        {
                            //            if (QSR.Trade.Price > Trades.Max(x => x.Price))
                            //            {
                            //                QSR.Code = 10;
                            //                QSR.Message = "暂无可用中介";
                            //                break;
                            //            }
                            //            else
                            //            {
                            //                t = tmpTrades.FirstOrDefault(x => x.Price == QSR.Trade.Price);
                            //                if (t == null)
                            //                {
                            //                    t = t = tmpTrades.Last();
                            //                }
                            //                else
                            //                {
                            //                    bFindSamePrice = true;
                            //                }
                            //            }
                            //        }
                            //        else
                            //        {
                            //            if (QSR.Trade.Price < Trades.Min(x => x.Price))
                            //            {
                            //                QSR.Code = 10;
                            //                QSR.Message = "暂无可用中介";
                            //                break;
                            //            }
                            //            else
                            //            {
                            //                t = tmpTrades.FirstOrDefault(x => x.Price == QSR.Trade.Price);
                            //                if (t == null)
                            //                {
                            //                    t = t = tmpTrades.First();
                            //                }
                            //                else
                            //                {
                            //                    bFindSamePrice = true;
                            //                }
                            //            }
                            //        }
                            //        if (t == null)
                            //        {
                            //            QSR.Code = 10;
                            //            QSR.Message = "暂无可用中介";
                            //            break;
                            //        }
                            //        brokerid = t.BrokerID;
                            //        string dtDate;
                            //        if (!bFindSamePrice)
                            //        {
                            //            dtDate = t.DeliveryDate.Month.ToString() + "月" + t.DeliveryDate.Day.ToString() + "日";
                            //            QSR.Trade.Command = $"T{t.DailyID:D3} {t.TsCode} {t.Price} {dtDate}+0 {t.Volume / 1000}k 改 ";
                            //            if (QSR.Trade.Price != t.Price)
                            //            {
                            //                QSR.Trade.Command += $"{QSR.Trade.Price} ";
                            //            }
                            //            if (QSR.Trade.DeliveryDate != t.DeliveryDate)
                            //            {
                            //                dtDate = QSR.Trade.DeliveryDate.Month.ToString() + "月" + QSR.Trade.DeliveryDate.Day.ToString() + "日";
                            //                QSR.Trade.Command += $"{dtDate} ";
                            //            }
                            //            if (QSR.Trade.Volume != t.Volume)
                            //            {
                            //                QSR.Trade.Command += $"{QSR.Trade.Volume / 1000}k ";
                            //            }
                            //        }
                            //        _userHelper.CancelUserTrade(t.UserTradeID, serverWebSocketFromClient.GetUserToken(t.UserID), out msg);
                            //        QSR.Message = msg;
                            //    }
                            //    else
                            //    {
                            //        switch (QSR.Trade.OrderType)
                            //        {
                            //            case UserTrade.UserTradeOrderTypeEnum.Bid:
                            //                AllowedBids = AllowedBids.Where(x => x.BidType == BidHistory.enumBidType.Bid).OrderByDescending(x => x.Price).ThenBy(x => x.Volume).ToList();
                            //                if (AllowedBids.Count > 0)
                            //                {
                            //                    brokerid = AllowedBids.First().BrokerId;
                            //                    foreach (var b in AllowedBids)
                            //                    {
                            //                        if (QSR.Trade.Price <= b.Price)
                            //                        {
                            //                            brokerid = b.BrokerId;
                            //                            break;
                            //                        }
                            //                    }
                            //                }
                            //                else
                            //                {
                            //                    brokerid = UserData.Single(y => y.UserID == QSR.UserID).BrokerList.First();
                            //                }
                            //                break;
                            //            case UserTrade.UserTradeOrderTypeEnum.Ofr:
                            //                AllowedBids = AllowedBids.Where(x => x.BidType == BidHistory.enumBidType.Ofr).OrderBy(x => x.Price).ThenBy(x => x.Volume).ToList();
                            //                if (AllowedBids.Count > 0)
                            //                {
                            //                    brokerid = AllowedBids.First().BrokerId;
                            //                    foreach (var b in AllowedBids)
                            //                    {
                            //                        if (QSR.Trade.Price >= b.Price)
                            //                        {
                            //                            brokerid = b.BrokerId;
                            //                            break;
                            //                        }
                            //                    }
                            //                }
                            //                else
                            //                {
                            //                    brokerid = UserData.Single(y => y.UserID == QSR.UserID).BrokerList.First();
                            //                }
                            //                break;
                            //            default:
                            //                break;
                            //        }
                            //    }
                            //}
                            //else
                            //{
                            //    chat = Receivers.Single(x => x.Id == QSR.Trade.ReceiverId);
                            //    tmpTrade = Trades.FirstOrDefault(x => x.TsCode == QSR.Trade.TsCode & x.OrderType == QSR.Trade.OrderType & x.OnHoldVolume > 0 & x.BrokerID == chat.Brokerid);
                            //    if (tmpTrade != null)
                            //    {
                            //        if (tmpTrade.Price != QSR.Trade.Price)
                            //        {
                            //            brokerid = 0;
                            //            List<BidHistory> AllowedBids = ServerWebSocketHelper.GetBidHistories(QSR.Trade.TsCode);
                            //            AllowedBids = AllowedBids.Where(x => UserData.Single(y => y.UserID == QSR.UserID).BrokerList.Contains(x.BrokerId)).ToList();
                            //            AllowedBids = AllowedBids.Where(x => !Trades.Where(y => y.OnHoldVolume > 0 & y.TsCode == QSR.Trade.TsCode & y.OrderType == QSR.Trade.OrderType).GroupBy(z => z.BrokerID).Select(z => z.Key).Contains(x.BrokerId)).ToList();
                            //            if (AllowedBids.Count == 0)
                            //            {
                            //                bool bFindSamePrice = false;
                            //                List<UserTrade> tmpTrades = Trades.Where(x => x.TsCode == QSR.Trade.TsCode & x.OrderType == QSR.Trade.OrderType).OrderBy(x => x.Price).ToList();
                            //                UserTrade t = null;
                            //                if (QSR.Trade.OrderType == UserTrade.UserTradeOrderTypeEnum.Bid)
                            //                {
                            //                    if (QSR.Trade.Price > Trades.Max(x => x.Price))
                            //                    {
                            //                        QSR.Code = 10;
                            //                        QSR.Message = "暂无可用中介";
                            //                        break;
                            //                    }
                            //                    else
                            //                    {
                            //                        t = tmpTrades.FirstOrDefault(x => x.Price == QSR.Trade.Price);
                            //                        if (t == null)
                            //                        {
                            //                            t = t = tmpTrades.Last();
                            //                        }
                            //                        else
                            //                        {
                            //                            bFindSamePrice = true;
                            //                        }
                            //                    }
                            //                }
                            //                else
                            //                {
                            //                    if (QSR.Trade.Price < Trades.Min(x => x.Price))
                            //                    {
                            //                        QSR.Code = 10;
                            //                        QSR.Message = "暂无可用中介";
                            //                        break;
                            //                    }
                            //                    else
                            //                    {
                            //                        t = tmpTrades.FirstOrDefault(x => x.Price == QSR.Trade.Price);
                            //                        if (t == null)
                            //                        {
                            //                            t = t = tmpTrades.First();
                            //                        }
                            //                        else
                            //                        {
                            //                            bFindSamePrice = true;
                            //                        }
                            //                    }
                            //                }
                            //                if (t == null)
                            //                {
                            //                    QSR.Code = 10;
                            //                    QSR.Message = "暂无可用中介";
                            //                    break;
                            //                }
                            //                brokerid = t.BrokerID;
                            //                string dtDate = QSR.Trade.DeliveryDate.Month.ToString() + "月" + QSR.Trade.DeliveryDate.Day.ToString() + "日";
                            //                if (!bFindSamePrice)
                            //                {
                            //                    QSR.Trade.Command = $"ref T{t.DailyID:D3} {t.TsCode} {t.Price} {t.Volume / 1000}k 若撤单成功则 __TID__ {QSR.Trade.DealType} {QSR.Trade.TsCode.Replace(".IB", "")} {QSR.Trade.Price} {dtDate}+0 {QSR.Trade.Volume / 1000}k";
                            //                }
                            //                _userHelper.CancelUserTrade(t.UserTradeID, serverWebSocketFromClient.GetUserToken(t.UserID), out msg);
                            //                QSR.Message = msg;
                            //            }
                            //        }
                            //        else
                            //        {
                            //            brokerid = (int)chat.Brokerid;
                            //        }
                            //    }
                            //    else
                            //    {
                            //        brokerid = (int)chat.Brokerid;
                            //    }
                            //}
                            chat = Receivers.FirstOrDefault(x => x.Brokerid == brokerid);
                            if (chat == null)
                            {
                                //QSR.Message = "未找到可用中介";
                                //QSR.Code = 6;
                                //serverWebSocketFromClient.SendResponseToClient(QSR);
                                //return;
                                //没找到对应中介
                            }

                            if (brokerid == -1)
                            {
                                brokerid = null;
                                QSR.Trade.ChatID = null;
                                QSR.Trade.Broker = null;


                                QSR.Trade.BrokerID = brokerid;
                                QSR.Trade.ReceiverId = null;
                                //chat.OrderInProgress = true;
                                QSR.Trade.Time = DateTime.Now;
                                QSR.Trade.UserName = UserData.Single(x => x.UserID == QSR.UserID).UserName;
                            }
                            else
                            {
                                QSR.Trade.ChatID = chat.ChatId;
                                QSR.Trade.Broker = chat.Company;


                                QSR.Trade.BrokerID = brokerid;

                                QSR.Trade.ReceiverId = chat.Id;
                                //chat.OrderInProgress = true;

                                QSR.Trade.Time = DateTime.Now;


                                QSR.Trade.UserName = UserData.Single(x => x.UserID == QSR.UserID).UserName;
                            }



                            string changePriceIds = string.Empty;
                            int realBrokerId = 0;
                            string realOrderMsg = string.Empty;
                            result = _userHelper.AddUserTrade(QSR.Trade, QSR.Token, out UserTradeID, out msg, out ActualVolume, ref changePriceIds, out realBrokerId, out realOrderMsg);
                            switch (result)
                            {
                                case 0:
                                    //_dailyData.BondHelperSysLog(QSR.UserID, "Lily下单成功," + msg, UserTradeID);
                                    QSR.Trade.BrokerID = realBrokerId;
                                    QSR.Trade.OnHoldVolume = ActualVolume;
                                    QSR.Trade.Volume = ActualVolume;
                                    QSR.Message = msg;
                                    break;
                                case 1:
                                    QSR.Message = msg;
                                    QSR.Code = 6;
                                    QSR.DataType = QuanYiServerBaseClass.DataTypeEnum.Order;
                                    //_dailyData.BondHelperSysLog(QSR.UserID, "Lily下单失败, " + msg, 0);
                                    break;
                                case 2:
                                    QSR.Code = 4;
                                    QSR.Message = msg;
                                    //_dailyData.BondHelperSysLog(QSR.UserID, "Lily下单成功," + msg, UserTradeID);
                                    QSR.Trade.Volume = ActualVolume;
                                    QSR.Trade.OnHoldVolume = ActualVolume;
                                    break;

                                case 3:
                                    QSR.Code = 11;
                                    QSR.Message = "发起重定向改价操作" + msg;
                                    //_dailyData.BondHelperSysLog(QSR.UserID, "Lily发起重定向改价操作," + msg, UserTradeID);
                                    QSR.Trade.Volume = ActualVolume;
                                    QSR.Trade.OnHoldVolume = ActualVolume;
                                    QSR.ChangePriceIds = changePriceIds;
                                    break;
                                default:
                                    break;
                            }
                            OrderLog += "下单相关：" + QSR.Trade.Command + "回应：" + QSR.Message + "\r\n";
                            QSR.Trade.UserTradeID = UserTradeID;

                            if (QSR.Code != 6 && QSR.Code != 11)
                            {
                                CurrentDailyID++;
                                QSR.Trade.DailyID = CurrentDailyID;

                                if (QSR.Trade.BrokerID == null && !string.IsNullOrEmpty(realOrderMsg))//对于自动特殊赋值一下
                                {
                                    JObject obj = JObject.Parse(realOrderMsg);
                                    int userTradeId = (int)obj["userTradeId"];
                                    string tradeNum = (string)obj["tradeNum"];
                                    string relativeNum = (string)obj["relativeNum"];
                                    string sourceNum = (string)obj["sourceNum"];
                                    int isYouxian = (int)obj["isYouxian"];
                                    int youxianLevel = (int)obj["youxianLevel"];
                                    string direction = (string)obj["direction"];
                                    string tscode = (string)obj["tscode"];
                                    int volume = (int)obj["volume"];
                                    string finishVolume = (string)obj["finishVolume"];
                                    int restVolume = (int)obj["restVolume"];
                                    decimal price = (decimal)obj["price"];
                                    double worstPrice = (double)obj["worstPrice"];
                                    DateTime deliveryTime = (DateTime)obj["deliveryTime"];
                                    string deliverySpeed = (string)obj["deliverySpeed"];
                                    int createBy = (int)obj["createBy"];
                                    DateTime createTime = (DateTime)obj["createTime"];
                                    int? updateBy = (int?)obj["updateBy"];
                                    DateTime? updateTime = (DateTime?)obj["updateTime"];
                                    string remark = (string)obj["remark"];
                                    int userId = (int)obj["userId"];
                                    int status = (int)obj["status"];
                                    bool forward = (bool)obj["forward"];
                                    int parentId = (int)obj["parentId"];
                                    string orderType = (string)obj["orderType"];
                                    string qiangpingId = (string)obj["qiangpingId"];
                                    int brokerId1 = (int)obj["brokerId"];
                                    string channelId = (string)obj["channelId"];
                                    int version = (int)obj["version"];
                                    string gaijiaTradeIds = (string)obj["gaijiaTradeIds"];
                                    string message = (string)obj["message"];
                                    string target = (string)obj["target"];
                                    QSR.Trade.ChannelID = channelId;
                                    QSR.Trade.BrokerID = brokerId1;
                                    QSR.Trade.UserTradeID = createBy;
                                    QSR.Trade.Volume = volume;
                                    QSR.Trade.OnHoldVolume = restVolume;
                                    QSR.Trade.Price = price;
                                    QSR.Trade.Status = status;
                                    QSR.Trade.UserID = userId;
                                    QSR.Trade.Time = createTime;
                                    QSR.Trade.TsCode = tscode;
                                    QSR.Trade.Broker = Receivers.Where(o => o.Brokerid == brokerId1).FirstOrDefault().Company;
                                    QSR.Trade.ChatID = Receivers.Where(o => o.Brokerid == brokerId1).FirstOrDefault().ChatId;
                                    QSR.Trade.ReceiverId = Receivers.Where(o => o.Brokerid == brokerId1).FirstOrDefault().Id;
                                }
                                //if (!_dailyData.AddUserTrade(QSR.Trade, out msg))
                                //{
                                //    QSR.Message = msg;
                                //    QSR.Code = 6;
                                //    //MessageBox.Show("询价单已发送，但创建询价单失败", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                //    _dailyData.BondHelperSysLog(QSR.UserID, "BondHelper下单失败" + msg, UserTradeID);
                                //}
                                //else
                                //{
                                //    _dailyData.BondHelperSysLog(QSR.UserID, "BondHelper下单成功" + msg, UserTradeID);
                                //}
                                QSR.Trade.StatusText = "已接收";
                                //PrismApplication.Current.Dispatcher.Invoke(() =>
                                //{
                                //    Trades.Insert(0, QSR.Trade); // 在 UI 线程上插入元素到 Trades 集合
                                //});
                                if (QSR.Trade.Command == "")
                                {
                                    string dtDate = QSR.Trade.DeliveryDate.Month.ToString() + "月" + QSR.Trade.DeliveryDate.Day.ToString() + "日";
                                    QSR.Trade.Command = $"T{QSR.Trade.DailyID:D3} {QSR.Trade.DealType} {QSR.Trade.TsCode.Replace(".IB", "")} {QSR.Trade.Price} {dtDate}+0 {QSR.Trade.Volume / 1000}k";
                                }
                                else
                                {
                                    QSR.Trade.Command = QSR.Trade.Command.Replace("__TID__", $"T{QSR.Trade.DailyID.ToString("D3")}");
                                }
                            }
                            if (QSR.Code == 0 || QSR.Code == 2|| QSR.Code == 4)
                            {

                                //询价单发送给lily
                                if (QSR != null && SendMessage(QSR, 1))
                                {
                                    ChatMessage chatMessage = new ChatMessage() { BrokerId = QSR.Trade.BrokerID, ChannelId = QSR.Trade.ChannelID, ChatMessageInfo = QSR.Message, TradeId = QSR.Trade.UserTradeID, ChatId = QSR.Trade.UserID };
                                    this.SaveMessageToLily(0, chatMessage);
                                }

                            }
                        }
                        catch (Exception ex)
                        {
                            AppLog.WriteError(ex.Message + "QuanyiServer" + "Socket_QuanYiClientMessageEvent", ex.StackTrace);
                            //_dailyData.BondHelperSysLog(QSR.UserID, "创建订单，" + ex.Message, QSR.Trade.UserTradeID);
                            QSR.Code = 7;
                            QSR.Message = ex.Message;
                            //serverWebSocketFromClient.SendResponseToClient(QSR);
                        }
                        break;
                    case QuanYiServerBaseClass.DataTypeEnum.ChangePrice:



                        //tmpTrade = Trades.FirstOrDefault(x => x.UserTradeID == QSR.Trade.UserTradeID);
                        //if (tmpTrade == null)
                        //{
                        //    //_dailyData.BondHelperSysLog(QSR.UserID, "Lily改价失败 - 无法找到该笔订单", tmpTrade.UserTradeID);
                        //    QSR.Code = 2;
                        //    QSR.Message = "无法找到该笔订单";
                        //    break;
                        //}
                        //if (tmpTrade.Status != 0 & tmpTrade.Status != 1 & tmpTrade.Status != 4)
                        //{
                        //    _dailyData.BondHelperSysLog(QSR.UserID, "Lily改价失败 - 该单已成交", tmpTrade.UserTradeID);
                        //    QSR.Code = 2;
                        //    QSR.Message = "该单已成交，无法改价";
                        //}
                        //else
                        //{
                        //    string dtDate = tmpTrade.DeliveryDate.Month.ToString() + "月" + tmpTrade.DeliveryDate.Day.ToString() + "日";
                        //    QSR.Trade.Command = $"T{QSR.Trade.DailyID:D3} {QSR.Trade.TsCode} {tmpTrade.Price} {dtDate}+0 {QSR.Trade.Volume / 1000}k 改 ";
                        //    if (QSR.Trade.Price != tmpTrade.Price)
                        //    {
                        //        QSR.Trade.Command += $"{QSR.Trade.Price} ";
                        //    }
                        //    if (QSR.Trade.DeliveryDate != tmpTrade.DeliveryDate)
                        //    {
                        //        dtDate = QSR.Trade.DeliveryDate.Month.ToString() + "月" + QSR.Trade.DeliveryDate.Day.ToString() + "日";
                        //        QSR.Trade.Command += $"{dtDate} ";
                        //    }
                        //    if (QSR.Trade.Volume != tmpTrade.Volume)
                        //    {
                        //        QSR.Trade.Command += $"{QSR.Trade.Volume / 1000}k ";
                        //    }
                        string returnMsg = string.Empty;
                        if (!_userHelper.ModifyUserTrade(QSR.Trade, QSR.Token, out msg, out returnMsg))
                        {
                            //_dailyData.BondHelperSysLog(QSR.UserID, "Lily改价失败", tmpTrade.UserTradeID);
                            QSR.Code = 2;
                            QSR.Message = "Lily改价失败" + returnMsg;
                            break;
                        }
                        else
                        {
                            QSR.Code = 0;
                            QSR.Message = msg;

                            //改价存到lily
                            if (QSR != null && SendMessage(QSR, 1))
                            {
                                ChatMessage chatMessage = new ChatMessage() { BrokerId = QSR.Trade.BrokerID, ChannelId = QSR.Trade.ChannelID, ChatMessageInfo = msg, TradeId = QSR.Trade.UserTradeID, ChatId = int.Parse(QSR.Trade.ChatID) };
                                this.SaveMessageToLily(0, chatMessage);
                            }
                        }
                        OrderLog += "改价相关：" + msg + "回应：" + QSR.Message + "\r\n";

                        //QSR.Code = 0;
                        //QSR.Message = "改价指令已发送";

                        break;
                    case QuanYiServerBaseClass.DataTypeEnum.ChangePriceConfirm:
                        tmpTrade = Trades.FirstOrDefault(x => x.UserTradeID == QSR.Trade.UserTradeID);
                        if (tmpTrade == null)
                        {
                            //_dailyData.BondHelperSysLog(QSR.UserID, "Lily改价失败 - 无法找到该笔订单", tmpTrade.UserTradeID);
                            QSR.Code = 2;
                            QSR.Message = "无法找到该笔订单";
                            break;
                        }
                        if (tmpTrade.Status != 0 & tmpTrade.Status != 1 & tmpTrade.Status != 4)
                        {
                            QSR.Code = 2;
                            QSR.Message = "该单已成交，无法改价";
                        }
                        else
                        {
                            //string returnMsg = string.Empty;
                            if (!_userHelper.ModifyUserTrade(QSR.Trade, QSR.Token, out msg, out returnMsg))
                            {
                                //_dailyData.BondHelperSysLog(QSR.UserID, "Lily改价失败", tmpTrade.UserTradeID);
                                QSR.Code = 2;
                                QSR.Message = returnMsg;
                                break;
                            }
                            if (!_dailyData.UpdateUserTrade(QSR.Trade))
                            {
                                QSR.Code = 2;
                                QSR.Message = "改价失败";
                                break;
                            }

                            //if (!_dailyData.UpdateUserTrade(tmpTrade))
                            //{
                            //    QSR.Code = 2;
                            //    QSR.Message = "修改BondHelper询价单失败";
                            //    AppLog.WriteError($"改价：修改BondHelper询价单失败{QSR.Trade.Command},{QSR.Trade.Target}" + QSR.Trade.UserTradeID.ToString());
                            //    _dailyData.BondHelperSysLog(QSR.UserID, "修改BondHelper询价单失败", tmpTrade.UserTradeID);
                            //    break;
                            //}
                            //_dailyData.BondHelperSysLog(QSR.UserID, "改价成功", tmpTrade.UserTradeID);
                            tmpTrade.Price = QSR.Trade.Price;
                            QSR.Code = 0;
                            QSR.Message = "订单已更新";
                        }
                        break;
                    case QuanYiServerBaseClass.DataTypeEnum.Withdraw:
                        //tmpTrade = Trades.FirstOrDefault(x => x.UserTradeID == QSR.Trade.UserTradeID);
                        //if (tmpTrade == null)
                        //{
                        //    _dailyData.BondHelperSysLog(QSR.UserID, "撤单失败 - 无法找到该笔订单", QSR.Trade.UserTradeID);
                        //    QSR.Code = 3;
                        //    QSR.Message = "无法找到该笔订单";
                        //    break;
                        //}
                        //if (tmpTrade.Status != 0 & tmpTrade.Status != 1 & tmpTrade.Status != 4)
                        //{
                        //    QSR.Code = 2;
                        //    QSR.Message = "该单已成交，无法改价";
                        //}
                        //else
                        //{
                        //    string returnMsg1 = string.Empty;
                        //    QSR.Trade.Command = $"ref T{QSR.Trade.DailyID:D3} {QSR.Trade.TsCode} {QSR.Trade.Price} {QSR.Trade.OnHoldVolume / 1000}k";
                        string returnMsg1 = string.Empty;
                        if (!_userHelper.CancelUserTrade(QSR.Trade.UserTradeID, QSR.Token, out msg, out returnMsg1))
                        {
                            //_dailyData.BondHelperSysLog(QSR.UserID, "Lily撤单失败",QSR.Trade.UserTradeID);
                            QSR.Code = 3;
                            QSR.Message = "Lily撤单失败" + msg;
                            break;
                        }
                        else
                        {
                            //_dailyData.BondHelperSysLog(QSR.UserID, "撤单成功", QSR.Trade.UserTradeID);
                            QSR.Code = 0;
                            QSR.Message = msg;
                            QSR.Trade.Status = 5;
                            QSR.Trade.StatusText = "已撤单";
                            QSR.Trade.Status = 5;
                            QSR.Trade.StatusText = "已撤单";



                            //撤单存到lily
                            if (QSR != null && SendMessage(QSR, 1))
                            {
                                ChatMessage chatMessage = new ChatMessage() { BrokerId = QSR.Trade.BrokerID, ChannelId = QSR.Trade.ChannelID, ChatMessageInfo = msg, TradeId = QSR.Trade.UserTradeID, ChatId = QSR.Trade.UserID };
                                this.SaveMessageToLily(0, chatMessage);
                            }


                        }
                        OrderLog += "撤单相关：" + QSR.Trade.Command + "回应：" + QSR.Message + "\r\n";

                        break;
                    //withdrawed去掉就行，2024/06/26
                    //case QuanYiServerBaseClass.DataTypeEnum.Withdrawed:
                    //    tmpTrade = Trades.FirstOrDefault(x => x.UserTradeID == QSR.Trade.UserTradeID);
                    //    if (tmpTrade == null)
                    //    {
                    //        _dailyData.BondHelperSysLog(QSR.UserID, "撤单失败 - 无法找到该笔订单", tmpTrade.UserTradeID);
                    //        QSR.Code = 3;
                    //        QSR.Message = "无法找到该笔订单";
                    //        break;
                    //    }
                    //    if (tmpTrade.Status != 0 & tmpTrade.Status != 1 & tmpTrade.Status != 4)
                    //    {
                    //        QSR.Code = 2;
                    //        QSR.Message = "该单已成交，无法改价";
                    //    }
                    //    else
                    //    {
                    //        if (!_userHelper.CancelUserTrade(QSR.Trade.UserTradeID, QSR.Token, out msg))
                    //        {
                    //            _dailyData.BondHelperSysLog(QSR.UserID, "Lily撤单失败", tmpTrade.UserTradeID);
                    //            QSR.Code = 3;
                    //            QSR.Message = "Lily撤单失败";
                    //            break;
                    //        }
                    //        else
                    //        {
                    //            _dailyData.BondHelperSysLog(QSR.UserID, "撤单成功", tmpTrade.UserTradeID);
                    //            QSR.Code = 0;
                    //            QSR.Message = "撤单成功";
                    //            QSR.Trade.Status = 5;
                    //            QSR.Trade.StatusText = "已撤单";
                    //            tmpTrade.Status = 5;
                    //            tmpTrade.StatusText = "已撤单";
                    //        }
                    //    }
                    //    break;
                    //case QuanYiServerBaseClass.DataTypeEnum.BackdatedOrder:
                    //    result = userhepler.AddUserTrade(QSR.Trade, QSR.Token, out UserTradeID, out msg, out ActualVolume);
                    //    switch (result)
                    //    {
                    //        case 0:
                    //            daily.BondHelperSysLog(QSR.UserID, "Lily下单成功," + msg, UserTradeID);
                    //            QSR.Trade.Volume = ActualVolume;
                    //            break;
                    //        case 1:
                    //            QSR.Message = msg;
                    //            QSR.Code = 6;
                    //            daily.BondHelperSysLog(QSR.UserID, "Lily下单失败, " + msg, 0);
                    //            break;
                    //        case 2:
                    //            QSR.Message = msg;
                    //            QSR.Code = 4;
                    //            QSR.Trade.Volume = ActualVolume;
                    //            daily.BondHelperSysLog(QSR.UserID, "Lily下单成功," + msg, UserTradeID);
                    //            break;
                    //        default:
                    //            break;
                    //    }
                    //    QSR.Trade.UserTradeID = UserTradeID;

                    //    break;
                    //case QuanYiServerBaseClass.DataTypeEnum.Trade:
                    //    tmpTrade = Trades.FirstOrDefault(x => x.UserTradeID == QSR.Trade.UserTradeID);
                    //    if (tmpTrade == null)
                    //    {
                    //        daily.BondHelperSysLog(QSR.UserID, "撤单失败 - 无法找到该笔订单", tmpTrade.UserTradeID);
                    //        QSR.Code = 3;
                    //        QSR.Message = "无法找到该笔订单";
                    //        break;
                    //    }
                    //    tmpTrade.OnHoldVolume = QSR.Trade.OnHoldVolume;
                    //    tmpTrade.Status = QSR.Trade.Status;
                    //    tmpTrade.StatusText = QSR.Trade.StatusText;
                    //    daily.BondHelperSysLog(QSR.UserID, "Lily成交,", tmpTrade.UserTradeID);
                    //    break;
                    case QuanYiServerBaseClass.DataTypeEnum.PingCang:
                        if (QSR.Trade.BrokerID == -1)
                        {
                            QSR.Trade.BrokerID = null;
                            QSR.Trade.ChatID = null;
                            QSR.Trade.Broker = null;


                            QSR.Trade.ReceiverId = null;
                            //chat.OrderInProgress = true;
                            QSR.Trade.Time = DateTime.Now;
                            QSR.Trade.UserName = UserData.Single(x => x.UserID == QSR.UserID).UserName;
                        }
                        int brokerId = 0;
                        int pingCangRes = _userHelper.PingCangUserTrade(QSR.Trade, QSR.Token, out msg, out brokerId);

                        switch (pingCangRes)
                        {
                            case 0:
                                QSR.Code = 0;
                                QSR.Trade.BrokerID = brokerId;
                                QSR.Trade.ChannelID = Receivers.Where(o => o.Brokerid == brokerId).FirstOrDefault().ChannelId;
                                QSR.Trade.UserTradeID = QSR.Trade.UserTradeID;
                                QSR.Message = msg;
                                break;

                            case 3:
                                QSR.Code = 11;
                                QSR.Message = "发起重定向改价操作" + msg;
                                break;
                            default:
                                QSR.Message = msg;
                                break;
                        }
                        if (QSR.Code == 0)
                        {

                            if(string.IsNullOrEmpty(msg))
                            {
                                AppLog.WriteError("平仓单返回的消息为空，异常");
                                return;
                            }
                            //撤单存到lily
                            if (QSR != null && SendMessage(QSR, 1))
                            {
                                ChatMessage chatMessage = new ChatMessage() { BrokerId = QSR.Trade.BrokerID, ChannelId = QSR.Trade.ChannelID, ChatMessageInfo = msg, TradeId = QSR.Trade.UserTradeID, ChatId = QSR.Trade.UserID };
                                this.SaveMessageToLily(0, chatMessage);
                            }
                        }


                        break;


                    //case QuanYiServerBaseClass.DataTypeEnum.InitChatMessage:
                    //    foreach (var r in Receivers)
                    //    {
                    //        lock (r)
                    //        {
                    //            QuanYiOrderServerResponseClass msgQsr = new QuanYiOrderServerResponseClass();
                    //            msgQsr.UserID = QSR.UserID;
                    //            msgQsr.SessionID = QSR.SessionID;
                    //            msgQsr.BrokerID = r.BrokerID;
                    //            msgQsr.DataType = QuanYiServerBaseClass.DataTypeEnum.ChatMessage;
                    //            msgQsr.ChatImage = r.ChatMessage;
                    //            serverWebSocketFromClient.SendResponseToClient(msgQsr);
                    //        }
                    //    }
                    //    break;
                    case QuanYiServerBaseClass.DataTypeEnum.ChatMessage:
                        // 0代表普通消息，1代表下单的消息
                        //快捷回复存到lily
                        if ((QSR != null) && SendMessage(QSR, 0))
                        {

                            ChatMessage chatMessage = new ChatMessage() { BrokerId = QSR.BrokerID, ChatMessageInfo = QSR.ChatMessage, ChatId = QSR.UserID };
                            this.SaveMessageToLily(0, chatMessage);
                        }
                        break;

                    case QuanYiServerBaseClass.DataTypeEnum.ShakeWindow:
                        // 0代表普通消息，1代表下单的消息
                        //快捷回复存到lily
                        if ((QSR != null))
                        {

                            var broker = Receivers.Where(o=>o.Brokerid == QSR.BrokerID).FirstOrDefault();
                            if(broker!=null)
                            {
                                WindowShaking(broker.ChatId);
                            }
                        }
                        break;
                    //ChatReceiver r1 = Receivers.Single(x => x.BrokerID == QSR.BrokerID);
                    //if (r1 != null)
                    //{
                    //    UserTrade t = new UserTrade();
                    //    t.Broker = r1.Broker;
                    //    t.ChatID = r1.ChatID;
                    //    t.Command = QSR.Message;
                    //    t.ReceiverId = r1.id;
                    //    SendMessage(t);
                    //}
                    //break;
                    //case QuanYiServerBaseClass.DataTypeEnum.Deal:
                    //    if (serverWebSocketFromClient.UserTradeDeal(QSR.Trade, out msg))
                    //    {
                    //        QSR.Code = 0;
                    //    }
                    //    else
                    //    {
                    //        QSR.Code = 1;

                    //    }
                    //    QSR.Message = msg;
                    //    break;
                    //default:
                    //    break;
                    case QuanYiServerBaseClass.DataTypeEnum.RequestReview:
                        bool res = _dailyData.AddRequestReview(QSR);
                        if (res)
                        {
                            AppLog.WriteInfo("插入一条新的复核" + QSR.RequestReviewMessage);
                        }
                        else
                        {
                            AppLog.WriteError("插入一条新的复核失败" + QSR.RequestReviewMessage);
                        }
                        break;
                    default:
                        break;
                }

                AppLog.WriteInfo("发送QSR至客户端" + QSR.ToString());
                this.serverWebSocketFromClient?.SendResponseToClient(QSR);
                //this.serverWebSocketFromAdmin?.SendMessageToAdmins(QSR);

            }
            catch (Exception ex)
            {
                AppLog.WriteError(ex.Message + "QuanyiServer" + "Socket_QuanYiClientMessageEvent" + ex.StackTrace);
                //_dailyData.BondHelperSysLog(QSR.UserID, "客户端消息，" + ex.Message, QSR.Trade == null ? 0 : QSR.Trade.UserTradeID);
                QSR.Code = 7;
                QSR.Message = ex.Message;
                //serverWebSocketFromClient.SendResponseToClient(QSR);
            }

        }
        private void Websocket_QuanYiServerMessageEvent(QuanYiOrderServerResponseClass QSR)
        {
            try
            {
                _messageQueue.Enqueue(QSR);
            }
            catch (Exception ex)
            {
                AppLog.WriteError($"Websocket_QuanYiServerMessageEvent异常,{ex.StackTrace}---{ex.Message}");
            }
            //try
            //{
            //    UserTrade tmpTrade;
            //    TradeSimUser user;
            //    ChatReceiver chat;
            //    int result;
            //    int UserTradeID;
            //    string msg;
            //    int ActualVolume;

            //    AppLog.WriteFatal("收到客户端QSR" + QSR.ToString());
            //    //var tradesNew =  UserHelper.FindAllXunJiaOrdersAsync().Result;
            //    //var tradeModels = tradesNew.Select(trade => new UserTrade
            //    //{
            //    //    // 根据需要设置 UserTrade 对象的属性
            //    //    // 例如：
            //    //    BrokerID = trade.BrokerId,
            //    //    Status = trade.Status,
            //    //    Price = (decimal)trade.Price,
            //    //    Volume = (int.Parse)(trade.Volume),
            //    //    OnHoldVolume = (int.Parse)(trade.RestVolume),
            //    //    TsCode = trade.Tscode,
            //    //    Time = trade.CreateTime,
            //    //    DealType = trade.Direction == "bond_0" ? "买入" : (trade.Direction == "bond_1" ? "卖出" : "未知"), // 根据Direction设置DealType
            //    //    UserTradeID = trade.UserTradeId,
            //    //    ChannelID = trade.ChannelId,
            //    //    DeliveryDate = DateOnly.FromDateTime(trade.DeliveryTime),
            //    //    DeliverySpeed = trade.DeliverySpeed,
            //    //    Target = trade.Target
            //    //    // 其他属性赋值
            //    //}).ToList();

            //    //PrismApplication.Current.Dispatcher.Invoke(() => { Trades = tradeModels.ToObservableCollection(); });
            //    // 异步获取数据
            //    var tradesNew = UserHelper.FindAllXunJiaOrdersAsync().Result;

            //    if (tradesNew != null)
            //    {
            //        // 使用并行化处理数据
            //        var tradeModels = tradesNew.AsParallel().Select(trade => new UserTrade
            //        {
            //            BrokerID = trade.BrokerId,
            //            Status = trade.Status,
            //            Price = (decimal)trade.Price,
            //            Volume = int.Parse(trade.Volume),
            //            OnHoldVolume = int.Parse(trade.RestVolume),
            //            TsCode = trade.Tscode,
            //            Time = trade.CreateTime,
            //            DealType = trade.Direction == "bond_0" ? "买入" : (trade.Direction == "bond_1" ? "卖出" : "未知"),
            //            UserTradeID = trade.UserTradeId,
            //            ChannelID = trade.ChannelId,
            //            DeliveryDate = DateOnly.FromDateTime(trade.DeliveryTime),
            //            DeliverySpeed = trade.DeliverySpeed,
            //            Target = trade.Target
            //        }).ToList();

            //        // 在后台线程更新UI
            //        PrismApplication.Current.Dispatcher.Invoke(() =>
            //        {
            //            Trades = tradeModels.ToObservableCollection();
            //        });
            //    }
            //    else
            //    {
            //        AppLog.WriteFatal("未能获取交易数据");
            //    }
            //    switch (QSR.DataType)
            //    {
            //        case QuanYiServerBaseClass.DataTypeEnum.Login:
            //            //user = UserData.Single(x => x.UserID == QSR.UserID);
            //            //PrismApplication.Current.Dispatcher.Invoke(() =>
            //            //{
            //            //    user.Status = 1;
            //            //    user.LoginTime = DateTime.Now;
            //            //});
            //            //QSR.Code = 0;
            //            //QSR.Message = "OK";
            //            //if (user.UserStatus > SimTradeUserStatusEnmu.Normal)
            //            //{
            //            //    QSR.Code = 0;
            //            //    QSR.Message = ((int)user.UserStatus).ToString();
            //            //    QSR.DataType = QuanYiServerBaseClass.DataTypeEnum.UserStatusChange;
            //            //    QSR.Trade = new UserTrade();
            //            //    QSR.Trade.Time = user.DisabledTime;
            //            //}
            //            //OrderLog += "登录相关：" + QSR.UserID + "回应：" + QSR.Message + "\r\n";
            //            //serverWebSocketFromClient?.SendMessageToAdmin(QSR);
            //            break;
            //        case QuanYiServerBaseClass.DataTypeEnum.Logout:

            //            //user = UserData.Single(x => x.UserID == QSR.UserID);
            //            //PrismApplication.Current.Dispatcher.Invoke(() =>
            //            //{
            //            //    user.Status = 0;
            //            //    user.LogoutTime = DateTime.Now;
            //            //});
            //            //OrderLog += "登出相关：" + QSR.UserID + "回应：" + QSR.Message + "\r\n";

            //            return;
            //        case QuanYiServerBaseClass.DataTypeEnum.Order:
            //            try

            //            {
            //                tmpTrade = Trades.FirstOrDefault(x => x.Guid == QSR.Trade.Guid);
            //                if (tmpTrade != null)
            //                {
            //                    QSR.Code = 8;
            //                    QSR.Message = "订单已存在";
            //                    QSR.DataType = QuanYiServerBaseClass.DataTypeEnum.Order;
            //                    break;
            //                }

            //                //var s = UserData;
            //                //if (UserData.Single(x => x.UserID == QSR.UserID).UserStatus > (SimTradeUserStatusEnmu)1)
            //                //{
            //                //    QSR.Code = 10;
            //                //    QSR.Message = "用户已被禁";
            //                //    QSR.DataType = QuanYiServerBaseClass.DataTypeEnum.Order;
            //                //    break;
            //                //}
            //                QSR.Trade.Command = "";
            //                int? brokerid = QSR.Trade.BrokerID;
            //                //if (QSR.Trade.ReceiverId == 0)
            //                //{
            //                //    brokerid = 0;
            //                //    List<BidHistory> AllowedBids = ServerWebSocketHelper.GetBidHistories(QSR.Trade.TsCode);
            //                //    AllowedBids = AllowedBids.Where(x => UserData.Single(y => y.UserID == QSR.UserID).BrokerList.Contains(x.BrokerId)).ToList();
            //                //    AllowedBids = AllowedBids.Where(x => !Trades.Where(y => y.OnHoldVolume > 0 & y.TsCode == QSR.Trade.TsCode & y.OrderType == QSR.Trade.OrderType).GroupBy(z => z.BrokerID).Select(z => z.Key).Contains(x.BrokerId)).ToList();
            //                //    PrismApplication.Current.Dispatcher.Invoke(() =>
            //                //    {
            //                //        AllowedBids = AllowedBids
            //                //            .Where(x => !Trades
            //                //                .Where(y => y.OnHoldVolume > 0 && y.TsCode == QSR.Trade.TsCode && y.OrderType == QSR.Trade.OrderType)
            //                //                .GroupBy(z => z.BrokerID)
            //                //                .Select(z => z.Key)
            //                //                .Contains(x.BrokerId))
            //                //            .ToList();
            //                //    });
            //                //    if (AllowedBids.Count == 0)
            //                //    {
            //                //        List<UserTrade> tmpTrades = null;
            //                //        bool bFindSamePrice = false;
            //                //        PrismApplication.Current.Dispatcher.Invoke(() =>
            //                //        {
            //                //            tmpTrades = Trades.Where(x => x.TsCode == QSR.Trade.TsCode & x.OrderType == QSR.Trade.OrderType).OrderBy(x => x.Price).ToList();

            //                //        });
            //                //        //List<UserTrade> tmpTrades = Trades.Where(x => x.TsCode == QSR.Trade.TsCode & x.OrderType == QSR.Trade.OrderType).OrderBy(x => x.Price).ToList();
            //                //        UserTrade t = null;
            //                //        if (QSR.Trade.OrderType == UserTrade.UserTradeOrderTypeEnum.Bid)
            //                //        {
            //                //            if (QSR.Trade.Price > Trades.Max(x => x.Price))
            //                //            {
            //                //                QSR.Code = 10;
            //                //                QSR.Message = "暂无可用中介";
            //                //                break;
            //                //            }
            //                //            else
            //                //            {
            //                //                t = tmpTrades.FirstOrDefault(x => x.Price == QSR.Trade.Price);
            //                //                if (t == null)
            //                //                {
            //                //                    t = t = tmpTrades.Last();
            //                //                }
            //                //                else
            //                //                {
            //                //                    bFindSamePrice = true;
            //                //                }
            //                //            }
            //                //        }
            //                //        else
            //                //        {
            //                //            if (QSR.Trade.Price < Trades.Min(x => x.Price))
            //                //            {
            //                //                QSR.Code = 10;
            //                //                QSR.Message = "暂无可用中介";
            //                //                break;
            //                //            }
            //                //            else
            //                //            {
            //                //                t = tmpTrades.FirstOrDefault(x => x.Price == QSR.Trade.Price);
            //                //                if (t == null)
            //                //                {
            //                //                    t = t = tmpTrades.First();
            //                //                }
            //                //                else
            //                //                {
            //                //                    bFindSamePrice = true;
            //                //                }
            //                //            }
            //                //        }
            //                //        if (t == null)
            //                //        {
            //                //            QSR.Code = 10;
            //                //            QSR.Message = "暂无可用中介";
            //                //            break;
            //                //        }
            //                //        brokerid = t.BrokerID;
            //                //        string dtDate;
            //                //        if (!bFindSamePrice)
            //                //        {
            //                //            dtDate = t.DeliveryDate.Month.ToString() + "月" + t.DeliveryDate.Day.ToString() + "日";
            //                //            QSR.Trade.Command = $"T{t.DailyID:D3} {t.TsCode} {t.Price} {dtDate}+0 {t.Volume / 1000}k 改 ";
            //                //            if (QSR.Trade.Price != t.Price)
            //                //            {
            //                //                QSR.Trade.Command += $"{QSR.Trade.Price} ";
            //                //            }
            //                //            if (QSR.Trade.DeliveryDate != t.DeliveryDate)
            //                //            {
            //                //                dtDate = QSR.Trade.DeliveryDate.Month.ToString() + "月" + QSR.Trade.DeliveryDate.Day.ToString() + "日";
            //                //                QSR.Trade.Command += $"{dtDate} ";
            //                //            }
            //                //            if (QSR.Trade.Volume != t.Volume)
            //                //            {
            //                //                QSR.Trade.Command += $"{QSR.Trade.Volume / 1000}k ";
            //                //            }
            //                //        }
            //                //        _userHelper.CancelUserTrade(t.UserTradeID, serverWebSocketFromClient.GetUserToken(t.UserID), out msg);
            //                //        QSR.Message = msg;
            //                //    }
            //                //    else
            //                //    {
            //                //        switch (QSR.Trade.OrderType)
            //                //        {
            //                //            case UserTrade.UserTradeOrderTypeEnum.Bid:
            //                //                AllowedBids = AllowedBids.Where(x => x.BidType == BidHistory.enumBidType.Bid).OrderByDescending(x => x.Price).ThenBy(x => x.Volume).ToList();
            //                //                if (AllowedBids.Count > 0)
            //                //                {
            //                //                    brokerid = AllowedBids.First().BrokerId;
            //                //                    foreach (var b in AllowedBids)
            //                //                    {
            //                //                        if (QSR.Trade.Price <= b.Price)
            //                //                        {
            //                //                            brokerid = b.BrokerId;
            //                //                            break;
            //                //                        }
            //                //                    }
            //                //                }
            //                //                else
            //                //                {
            //                //                    brokerid = UserData.Single(y => y.UserID == QSR.UserID).BrokerList.First();
            //                //                }
            //                //                break;
            //                //            case UserTrade.UserTradeOrderTypeEnum.Ofr:
            //                //                AllowedBids = AllowedBids.Where(x => x.BidType == BidHistory.enumBidType.Ofr).OrderBy(x => x.Price).ThenBy(x => x.Volume).ToList();
            //                //                if (AllowedBids.Count > 0)
            //                //                {
            //                //                    brokerid = AllowedBids.First().BrokerId;
            //                //                    foreach (var b in AllowedBids)
            //                //                    {
            //                //                        if (QSR.Trade.Price >= b.Price)
            //                //                        {
            //                //                            brokerid = b.BrokerId;
            //                //                            break;
            //                //                        }
            //                //                    }
            //                //                }
            //                //                else
            //                //                {
            //                //                    brokerid = UserData.Single(y => y.UserID == QSR.UserID).BrokerList.First();
            //                //                }
            //                //                break;
            //                //            default:
            //                //                break;
            //                //        }
            //                //    }
            //                //}
            //                //else
            //                //{
            //                //    chat = Receivers.Single(x => x.Id == QSR.Trade.ReceiverId);
            //                //    tmpTrade = Trades.FirstOrDefault(x => x.TsCode == QSR.Trade.TsCode & x.OrderType == QSR.Trade.OrderType & x.OnHoldVolume > 0 & x.BrokerID == chat.Brokerid);
            //                //    if (tmpTrade != null)
            //                //    {
            //                //        if (tmpTrade.Price != QSR.Trade.Price)
            //                //        {
            //                //            brokerid = 0;
            //                //            List<BidHistory> AllowedBids = ServerWebSocketHelper.GetBidHistories(QSR.Trade.TsCode);
            //                //            AllowedBids = AllowedBids.Where(x => UserData.Single(y => y.UserID == QSR.UserID).BrokerList.Contains(x.BrokerId)).ToList();
            //                //            AllowedBids = AllowedBids.Where(x => !Trades.Where(y => y.OnHoldVolume > 0 & y.TsCode == QSR.Trade.TsCode & y.OrderType == QSR.Trade.OrderType).GroupBy(z => z.BrokerID).Select(z => z.Key).Contains(x.BrokerId)).ToList();
            //                //            if (AllowedBids.Count == 0)
            //                //            {
            //                //                bool bFindSamePrice = false;
            //                //                List<UserTrade> tmpTrades = Trades.Where(x => x.TsCode == QSR.Trade.TsCode & x.OrderType == QSR.Trade.OrderType).OrderBy(x => x.Price).ToList();
            //                //                UserTrade t = null;
            //                //                if (QSR.Trade.OrderType == UserTrade.UserTradeOrderTypeEnum.Bid)
            //                //                {
            //                //                    if (QSR.Trade.Price > Trades.Max(x => x.Price))
            //                //                    {
            //                //                        QSR.Code = 10;
            //                //                        QSR.Message = "暂无可用中介";
            //                //                        break;
            //                //                    }
            //                //                    else
            //                //                    {
            //                //                        t = tmpTrades.FirstOrDefault(x => x.Price == QSR.Trade.Price);
            //                //                        if (t == null)
            //                //                        {
            //                //                            t = t = tmpTrades.Last();
            //                //                        }
            //                //                        else
            //                //                        {
            //                //                            bFindSamePrice = true;
            //                //                        }
            //                //                    }
            //                //                }
            //                //                else
            //                //                {
            //                //                    if (QSR.Trade.Price < Trades.Min(x => x.Price))
            //                //                    {
            //                //                        QSR.Code = 10;
            //                //                        QSR.Message = "暂无可用中介";
            //                //                        break;
            //                //                    }
            //                //                    else
            //                //                    {
            //                //                        t = tmpTrades.FirstOrDefault(x => x.Price == QSR.Trade.Price);
            //                //                        if (t == null)
            //                //                        {
            //                //                            t = t = tmpTrades.First();
            //                //                        }
            //                //                        else
            //                //                        {
            //                //                            bFindSamePrice = true;
            //                //                        }
            //                //                    }
            //                //                }
            //                //                if (t == null)
            //                //                {
            //                //                    QSR.Code = 10;
            //                //                    QSR.Message = "暂无可用中介";
            //                //                    break;
            //                //                }
            //                //                brokerid = t.BrokerID;
            //                //                string dtDate = QSR.Trade.DeliveryDate.Month.ToString() + "月" + QSR.Trade.DeliveryDate.Day.ToString() + "日";
            //                //                if (!bFindSamePrice)
            //                //                {
            //                //                    QSR.Trade.Command = $"ref T{t.DailyID:D3} {t.TsCode} {t.Price} {t.Volume / 1000}k 若撤单成功则 __TID__ {QSR.Trade.DealType} {QSR.Trade.TsCode.Replace(".IB", "")} {QSR.Trade.Price} {dtDate}+0 {QSR.Trade.Volume / 1000}k";
            //                //                }
            //                //                _userHelper.CancelUserTrade(t.UserTradeID, serverWebSocketFromClient.GetUserToken(t.UserID), out msg);
            //                //                QSR.Message = msg;
            //                //            }
            //                //        }
            //                //        else
            //                //        {
            //                //            brokerid = (int)chat.Brokerid;
            //                //        }
            //                //    }
            //                //    else
            //                //    {
            //                //        brokerid = (int)chat.Brokerid;
            //                //    }
            //                //}
            //                chat = Receivers.FirstOrDefault(x => x.Brokerid == brokerid);
            //                if (chat == null)
            //                {
            //                    //QSR.Message = "未找到可用中介";
            //                    //QSR.Code = 6;
            //                    //serverWebSocketFromClient.SendResponseToClient(QSR);
            //                    //return;
            //                    //没找到对应中介
            //                }

            //                if (brokerid == -1)
            //                {
            //                    brokerid = null;
            //                    QSR.Trade.ChatID = null;
            //                    QSR.Trade.Broker = null;


            //                    QSR.Trade.BrokerID = brokerid;
            //                    QSR.Trade.ReceiverId = null;
            //                    //chat.OrderInProgress = true;
            //                    QSR.Trade.Time = DateTime.Now;
            //                    QSR.Trade.UserName = UserData.Single(x => x.UserID == QSR.UserID).UserName;
            //                }
            //                else
            //                {
            //                    QSR.Trade.ChatID = chat.ChatId;
            //                    QSR.Trade.Broker = chat.Company;


            //                    QSR.Trade.BrokerID = brokerid;

            //                    QSR.Trade.ReceiverId = chat.Id;
            //                    //chat.OrderInProgress = true;

            //                    QSR.Trade.Time = DateTime.Now;


            //                    QSR.Trade.UserName = UserData.Single(x => x.UserID == QSR.UserID).UserName;
            //                }



            //                string changePriceIds = string.Empty;
            //                int realBrokerId = 0;
            //                string realOrderMsg = string.Empty;
            //                result = _userHelper.AddUserTrade(QSR.Trade, QSR.Token, out UserTradeID, out msg, out ActualVolume, ref changePriceIds, out realBrokerId, out realOrderMsg);
            //                switch (result)
            //                {
            //                    case 0:
            //                        //_dailyData.BondHelperSysLog(QSR.UserID, "Lily下单成功," + msg, UserTradeID);
            //                        QSR.Trade.BrokerID = realBrokerId;
            //                        QSR.Trade.OnHoldVolume = ActualVolume;
            //                        QSR.Trade.Volume = ActualVolume;
            //                        QSR.Message = msg;
            //                        break;
            //                    case 1:
            //                        QSR.Message = msg;
            //                        QSR.Code = 6;
            //                        QSR.DataType = QuanYiServerBaseClass.DataTypeEnum.Order;
            //                        //_dailyData.BondHelperSysLog(QSR.UserID, "Lily下单失败, " + msg, 0);
            //                        break;
            //                    case 2:
            //                        QSR.Code = 4;
            //                        QSR.Message = msg;
            //                        //_dailyData.BondHelperSysLog(QSR.UserID, "Lily下单成功," + msg, UserTradeID);
            //                        QSR.Trade.Volume = ActualVolume;
            //                        QSR.Trade.OnHoldVolume = ActualVolume;
            //                        break;

            //                    case 3:
            //                        QSR.Code = 11;
            //                        QSR.Message = "发起重定向改价操作" + msg;
            //                        //_dailyData.BondHelperSysLog(QSR.UserID, "Lily发起重定向改价操作," + msg, UserTradeID);
            //                        QSR.Trade.Volume = ActualVolume;
            //                        QSR.Trade.OnHoldVolume = ActualVolume;
            //                        QSR.ChangePriceIds = changePriceIds;
            //                        break;
            //                    default:
            //                        break;
            //                }
            //                OrderLog += "下单相关：" + QSR.Trade.Command + "回应：" + QSR.Message + "\r\n";
            //                QSR.Trade.UserTradeID = UserTradeID;

            //                if (QSR.Code != 6 && QSR.Code != 11)
            //                {
            //                    CurrentDailyID++;
            //                    QSR.Trade.DailyID = CurrentDailyID;

            //                    if (QSR.Trade.BrokerID == null && !string.IsNullOrEmpty(realOrderMsg))//对于自动特殊赋值一下
            //                    {
            //                        JObject obj = JObject.Parse(realOrderMsg);
            //                        int userTradeId = (int)obj["userTradeId"];
            //                        string tradeNum = (string)obj["tradeNum"];
            //                        string relativeNum = (string)obj["relativeNum"];
            //                        string sourceNum = (string)obj["sourceNum"];
            //                        int isYouxian = (int)obj["isYouxian"];
            //                        int youxianLevel = (int)obj["youxianLevel"];
            //                        string direction = (string)obj["direction"];
            //                        string tscode = (string)obj["tscode"];
            //                        int volume = (int)obj["volume"];
            //                        string finishVolume = (string)obj["finishVolume"];
            //                        int restVolume = (int)obj["restVolume"];
            //                        decimal price = (decimal)obj["price"];
            //                        double worstPrice = (double)obj["worstPrice"];
            //                        DateTime deliveryTime = (DateTime)obj["deliveryTime"];
            //                        string deliverySpeed = (string)obj["deliverySpeed"];
            //                        int createBy = (int)obj["createBy"];
            //                        DateTime createTime = (DateTime)obj["createTime"];
            //                        int? updateBy = (int?)obj["updateBy"];
            //                        DateTime? updateTime = (DateTime?)obj["updateTime"];
            //                        string remark = (string)obj["remark"];
            //                        int userId = (int)obj["userId"];
            //                        int status = (int)obj["status"];
            //                        bool forward = (bool)obj["forward"];
            //                        int parentId = (int)obj["parentId"];
            //                        string orderType = (string)obj["orderType"];
            //                        string qiangpingId = (string)obj["qiangpingId"];
            //                        int brokerId1 = (int)obj["brokerId"];
            //                        string channelId = (string)obj["channelId"];
            //                        int version = (int)obj["version"];
            //                        string gaijiaTradeIds = (string)obj["gaijiaTradeIds"];
            //                        string message = (string)obj["message"];
            //                        string target = (string)obj["target"];
            //                        QSR.Trade.ChannelID = channelId;
            //                        QSR.Trade.BrokerID = brokerId1;
            //                        QSR.Trade.UserTradeID = createBy;
            //                        QSR.Trade.Volume = volume;
            //                        QSR.Trade.OnHoldVolume = restVolume;
            //                        QSR.Trade.Price = price;
            //                        QSR.Trade.Status = status;
            //                        QSR.Trade.UserID = userId;
            //                        QSR.Trade.Time = createTime;
            //                        QSR.Trade.TsCode = tscode;
            //                        QSR.Trade.Broker = Receivers.Where(o => o.Brokerid == brokerId1).FirstOrDefault().Company;
            //                        QSR.Trade.ChatID = Receivers.Where(o => o.Brokerid == brokerId1).FirstOrDefault().ChatId;
            //                        QSR.Trade.ReceiverId = Receivers.Where(o => o.Brokerid == brokerId1).FirstOrDefault().Id;
            //                    }
            //                    //if (!_dailyData.AddUserTrade(QSR.Trade, out msg))
            //                    //{
            //                    //    QSR.Message = msg;
            //                    //    QSR.Code = 6;
            //                    //    //MessageBox.Show("询价单已发送，但创建询价单失败", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            //                    //    _dailyData.BondHelperSysLog(QSR.UserID, "BondHelper下单失败" + msg, UserTradeID);
            //                    //}
            //                    //else
            //                    //{
            //                    //    _dailyData.BondHelperSysLog(QSR.UserID, "BondHelper下单成功" + msg, UserTradeID);
            //                    //}
            //                    QSR.Trade.StatusText = "已接收";
            //                    PrismApplication.Current.Dispatcher.Invoke(() =>
            //                    {
            //                        Trades.Insert(0, QSR.Trade); // 在 UI 线程上插入元素到 Trades 集合
            //                    });
            //                    if (QSR.Trade.Command == "")
            //                    {
            //                        string dtDate = QSR.Trade.DeliveryDate.Month.ToString() + "月" + QSR.Trade.DeliveryDate.Day.ToString() + "日";
            //                        QSR.Trade.Command = $"T{QSR.Trade.DailyID:D3} {QSR.Trade.DealType} {QSR.Trade.TsCode.Replace(".IB", "")} {QSR.Trade.Price} {dtDate}+0 {QSR.Trade.Volume / 1000}k";
            //                    }
            //                    else
            //                    {
            //                        QSR.Trade.Command = QSR.Trade.Command.Replace("__TID__", $"T{QSR.Trade.DailyID.ToString("D3")}");
            //                    }
            //                }
            //                if (QSR.Code == 0 || QSR.Code == 2)
            //                {

            //                    //询价单发送给lily
            //                    if (QSR != null && SendMessage(QSR, 1))
            //                    {
            //                        ChatMessage chatMessage = new ChatMessage() { BrokerId = QSR.Trade.BrokerID, ChannelId = QSR.Trade.ChannelID, ChatMessageInfo = QSR.Message, TradeId = QSR.Trade.UserTradeID, ChatId = QSR.Trade.UserID };
            //                        this.SaveMessageToLily(0, chatMessage);
            //                    }

            //                }
            //            }
            //            catch (Exception ex)
            //            {
            //                AppLog.WriteError(ex.Message + "QuanyiServer" + "Socket_QuanYiClientMessageEvent", ex.StackTrace);
            //                //_dailyData.BondHelperSysLog(QSR.UserID, "创建订单，" + ex.Message, QSR.Trade.UserTradeID);
            //                QSR.Code = 7;
            //                QSR.Message = ex.Message;
            //                //serverWebSocketFromClient.SendResponseToClient(QSR);
            //            }
            //            break;
            //        case QuanYiServerBaseClass.DataTypeEnum.ChangePrice:



            //            //tmpTrade = Trades.FirstOrDefault(x => x.UserTradeID == QSR.Trade.UserTradeID);
            //            //if (tmpTrade == null)
            //            //{
            //            //    //_dailyData.BondHelperSysLog(QSR.UserID, "Lily改价失败 - 无法找到该笔订单", tmpTrade.UserTradeID);
            //            //    QSR.Code = 2;
            //            //    QSR.Message = "无法找到该笔订单";
            //            //    break;
            //            //}
            //            //if (tmpTrade.Status != 0 & tmpTrade.Status != 1 & tmpTrade.Status != 4)
            //            //{
            //            //    _dailyData.BondHelperSysLog(QSR.UserID, "Lily改价失败 - 该单已成交", tmpTrade.UserTradeID);
            //            //    QSR.Code = 2;
            //            //    QSR.Message = "该单已成交，无法改价";
            //            //}
            //            //else
            //            //{
            //            //    string dtDate = tmpTrade.DeliveryDate.Month.ToString() + "月" + tmpTrade.DeliveryDate.Day.ToString() + "日";
            //            //    QSR.Trade.Command = $"T{QSR.Trade.DailyID:D3} {QSR.Trade.TsCode} {tmpTrade.Price} {dtDate}+0 {QSR.Trade.Volume / 1000}k 改 ";
            //            //    if (QSR.Trade.Price != tmpTrade.Price)
            //            //    {
            //            //        QSR.Trade.Command += $"{QSR.Trade.Price} ";
            //            //    }
            //            //    if (QSR.Trade.DeliveryDate != tmpTrade.DeliveryDate)
            //            //    {
            //            //        dtDate = QSR.Trade.DeliveryDate.Month.ToString() + "月" + QSR.Trade.DeliveryDate.Day.ToString() + "日";
            //            //        QSR.Trade.Command += $"{dtDate} ";
            //            //    }
            //            //    if (QSR.Trade.Volume != tmpTrade.Volume)
            //            //    {
            //            //        QSR.Trade.Command += $"{QSR.Trade.Volume / 1000}k ";
            //            //    }
            //            string returnMsg = string.Empty;
            //            if (!_userHelper.ModifyUserTrade(QSR.Trade, QSR.Token, out msg, out returnMsg))
            //            {
            //                //_dailyData.BondHelperSysLog(QSR.UserID, "Lily改价失败", tmpTrade.UserTradeID);
            //                QSR.Code = 2;
            //                QSR.Message = "Lily改价失败" + returnMsg;
            //                break;
            //            }
            //            else
            //            {
            //                QSR.Code = 0;
            //                QSR.Message = msg;

            //                //改价存到lily
            //                if (QSR != null && SendMessage(QSR, 1))
            //                {
            //                    ChatMessage chatMessage = new ChatMessage() { BrokerId = QSR.Trade.BrokerID, ChannelId = QSR.Trade.ChannelID, ChatMessageInfo = msg, TradeId = QSR.Trade.UserTradeID, ChatId = int.Parse(QSR.Trade.ChatID) };
            //                    this.SaveMessageToLily(0, chatMessage);
            //                }
            //            }
            //            OrderLog += "改价相关：" + msg + "回应：" + QSR.Message + "\r\n";

            //            //QSR.Code = 0;
            //            //QSR.Message = "改价指令已发送";

            //            break;
            //        case QuanYiServerBaseClass.DataTypeEnum.ChangePriceConfirm:
            //            tmpTrade = Trades.FirstOrDefault(x => x.UserTradeID == QSR.Trade.UserTradeID);
            //            if (tmpTrade == null)
            //            {
            //                //_dailyData.BondHelperSysLog(QSR.UserID, "Lily改价失败 - 无法找到该笔订单", tmpTrade.UserTradeID);
            //                QSR.Code = 2;
            //                QSR.Message = "无法找到该笔订单";
            //                break;
            //            }
            //            if (tmpTrade.Status != 0 & tmpTrade.Status != 1 & tmpTrade.Status != 4)
            //            {
            //                QSR.Code = 2;
            //                QSR.Message = "该单已成交，无法改价";
            //            }
            //            else
            //            {
            //                //string returnMsg = string.Empty;
            //                if (!_userHelper.ModifyUserTrade(QSR.Trade, QSR.Token, out msg, out returnMsg))
            //                {
            //                    //_dailyData.BondHelperSysLog(QSR.UserID, "Lily改价失败", tmpTrade.UserTradeID);
            //                    QSR.Code = 2;
            //                    QSR.Message = returnMsg;
            //                    break;
            //                }
            //                if (!_dailyData.UpdateUserTrade(QSR.Trade))
            //                {
            //                    QSR.Code = 2;
            //                    QSR.Message = "改价失败";
            //                    break;
            //                }

            //                //if (!_dailyData.UpdateUserTrade(tmpTrade))
            //                //{
            //                //    QSR.Code = 2;
            //                //    QSR.Message = "修改BondHelper询价单失败";
            //                //    AppLog.WriteError($"改价：修改BondHelper询价单失败{QSR.Trade.Command},{QSR.Trade.Target}" + QSR.Trade.UserTradeID.ToString());
            //                //    _dailyData.BondHelperSysLog(QSR.UserID, "修改BondHelper询价单失败", tmpTrade.UserTradeID);
            //                //    break;
            //                //}
            //                //_dailyData.BondHelperSysLog(QSR.UserID, "改价成功", tmpTrade.UserTradeID);
            //                tmpTrade.Price = QSR.Trade.Price;
            //                QSR.Code = 0;
            //                QSR.Message = "订单已更新";
            //            }
            //            break;
            //        case QuanYiServerBaseClass.DataTypeEnum.Withdraw:
            //            //tmpTrade = Trades.FirstOrDefault(x => x.UserTradeID == QSR.Trade.UserTradeID);
            //            //if (tmpTrade == null)
            //            //{
            //            //    _dailyData.BondHelperSysLog(QSR.UserID, "撤单失败 - 无法找到该笔订单", QSR.Trade.UserTradeID);
            //            //    QSR.Code = 3;
            //            //    QSR.Message = "无法找到该笔订单";
            //            //    break;
            //            //}
            //            //if (tmpTrade.Status != 0 & tmpTrade.Status != 1 & tmpTrade.Status != 4)
            //            //{
            //            //    QSR.Code = 2;
            //            //    QSR.Message = "该单已成交，无法改价";
            //            //}
            //            //else
            //            //{
            //            //    string returnMsg1 = string.Empty;
            //            //    QSR.Trade.Command = $"ref T{QSR.Trade.DailyID:D3} {QSR.Trade.TsCode} {QSR.Trade.Price} {QSR.Trade.OnHoldVolume / 1000}k";
            //            string returnMsg1 = string.Empty;
            //            if (!_userHelper.CancelUserTrade(QSR.Trade.UserTradeID, QSR.Token, out msg, out returnMsg1))
            //            {
            //                //_dailyData.BondHelperSysLog(QSR.UserID, "Lily撤单失败",QSR.Trade.UserTradeID);
            //                QSR.Code = 3;
            //                QSR.Message = "Lily撤单失败" + msg;
            //                break;
            //            }
            //            else
            //            {
            //                //_dailyData.BondHelperSysLog(QSR.UserID, "撤单成功", QSR.Trade.UserTradeID);
            //                QSR.Code = 0;
            //                QSR.Message = msg;
            //                QSR.Trade.Status = 5;
            //                QSR.Trade.StatusText = "已撤单";
            //                QSR.Trade.Status = 5;
            //                QSR.Trade.StatusText = "已撤单";



            //                //撤单存到lily
            //                if (QSR != null && SendMessage(QSR, 1))
            //                {
            //                    ChatMessage chatMessage = new ChatMessage() { BrokerId = QSR.Trade.BrokerID, ChannelId = QSR.Trade.ChannelID, ChatMessageInfo = msg, TradeId = QSR.Trade.UserTradeID, ChatId = QSR.Trade.UserID };
            //                    this.SaveMessageToLily(0, chatMessage);
            //                }


            //            }
            //            OrderLog += "撤单相关：" + QSR.Trade.Command + "回应：" + QSR.Message + "\r\n";

            //            break;
            //        //withdrawed去掉就行，2024/06/26
            //        //case QuanYiServerBaseClass.DataTypeEnum.Withdrawed:
            //        //    tmpTrade = Trades.FirstOrDefault(x => x.UserTradeID == QSR.Trade.UserTradeID);
            //        //    if (tmpTrade == null)
            //        //    {
            //        //        _dailyData.BondHelperSysLog(QSR.UserID, "撤单失败 - 无法找到该笔订单", tmpTrade.UserTradeID);
            //        //        QSR.Code = 3;
            //        //        QSR.Message = "无法找到该笔订单";
            //        //        break;
            //        //    }
            //        //    if (tmpTrade.Status != 0 & tmpTrade.Status != 1 & tmpTrade.Status != 4)
            //        //    {
            //        //        QSR.Code = 2;
            //        //        QSR.Message = "该单已成交，无法改价";
            //        //    }
            //        //    else
            //        //    {
            //        //        if (!_userHelper.CancelUserTrade(QSR.Trade.UserTradeID, QSR.Token, out msg))
            //        //        {
            //        //            _dailyData.BondHelperSysLog(QSR.UserID, "Lily撤单失败", tmpTrade.UserTradeID);
            //        //            QSR.Code = 3;
            //        //            QSR.Message = "Lily撤单失败";
            //        //            break;
            //        //        }
            //        //        else
            //        //        {
            //        //            _dailyData.BondHelperSysLog(QSR.UserID, "撤单成功", tmpTrade.UserTradeID);
            //        //            QSR.Code = 0;
            //        //            QSR.Message = "撤单成功";
            //        //            QSR.Trade.Status = 5;
            //        //            QSR.Trade.StatusText = "已撤单";
            //        //            tmpTrade.Status = 5;
            //        //            tmpTrade.StatusText = "已撤单";
            //        //        }
            //        //    }
            //        //    break;
            //        //case QuanYiServerBaseClass.DataTypeEnum.BackdatedOrder:
            //        //    result = userhepler.AddUserTrade(QSR.Trade, QSR.Token, out UserTradeID, out msg, out ActualVolume);
            //        //    switch (result)
            //        //    {
            //        //        case 0:
            //        //            daily.BondHelperSysLog(QSR.UserID, "Lily下单成功," + msg, UserTradeID);
            //        //            QSR.Trade.Volume = ActualVolume;
            //        //            break;
            //        //        case 1:
            //        //            QSR.Message = msg;
            //        //            QSR.Code = 6;
            //        //            daily.BondHelperSysLog(QSR.UserID, "Lily下单失败, " + msg, 0);
            //        //            break;
            //        //        case 2:
            //        //            QSR.Message = msg;
            //        //            QSR.Code = 4;
            //        //            QSR.Trade.Volume = ActualVolume;
            //        //            daily.BondHelperSysLog(QSR.UserID, "Lily下单成功," + msg, UserTradeID);
            //        //            break;
            //        //        default:
            //        //            break;
            //        //    }
            //        //    QSR.Trade.UserTradeID = UserTradeID;

            //        //    break;
            //        //case QuanYiServerBaseClass.DataTypeEnum.Trade:
            //        //    tmpTrade = Trades.FirstOrDefault(x => x.UserTradeID == QSR.Trade.UserTradeID);
            //        //    if (tmpTrade == null)
            //        //    {
            //        //        daily.BondHelperSysLog(QSR.UserID, "撤单失败 - 无法找到该笔订单", tmpTrade.UserTradeID);
            //        //        QSR.Code = 3;
            //        //        QSR.Message = "无法找到该笔订单";
            //        //        break;
            //        //    }
            //        //    tmpTrade.OnHoldVolume = QSR.Trade.OnHoldVolume;
            //        //    tmpTrade.Status = QSR.Trade.Status;
            //        //    tmpTrade.StatusText = QSR.Trade.StatusText;
            //        //    daily.BondHelperSysLog(QSR.UserID, "Lily成交,", tmpTrade.UserTradeID);
            //        //    break;
            //        case QuanYiServerBaseClass.DataTypeEnum.PingCang:
            //            if (QSR.Trade.BrokerID == -1)
            //            {
            //                QSR.Trade.BrokerID = null;
            //                QSR.Trade.ChatID = null;
            //                QSR.Trade.Broker = null;


            //                QSR.Trade.ReceiverId = null;
            //                //chat.OrderInProgress = true;
            //                QSR.Trade.Time = DateTime.Now;
            //                QSR.Trade.UserName = UserData.Single(x => x.UserID == QSR.UserID).UserName;
            //            }
            //            int brokerId = 0;
            //            int pingCangRes = _userHelper.PingCangUserTrade(QSR.Trade, QSR.Token, out msg, out brokerId);

            //            switch (pingCangRes)
            //            {
            //                case 0:
            //                    QSR.Code = 0;
            //                    QSR.Trade.BrokerID = brokerId;
            //                    QSR.Trade.ChannelID = Receivers.Where(o => o.Brokerid == brokerId).FirstOrDefault().ChannelId;
            //                    QSR.Trade.UserTradeID = QSR.Trade.UserTradeID;
            //                    QSR.Message = msg;
            //                    break;

            //                case 3:
            //                    QSR.Code = 11;
            //                    QSR.Message = "发起重定向改价操作" + msg;
            //                    break;
            //                default:
            //                    QSR.Message = msg;
            //                    break;
            //            }
            //            if (QSR.Code == 0)
            //            {

            //                //撤单存到lily
            //                if (QSR != null && SendMessage(QSR, 1))
            //                {
            //                    ChatMessage chatMessage = new ChatMessage() { BrokerId = QSR.Trade.BrokerID, ChannelId = QSR.Trade.ChannelID, ChatMessageInfo = msg, TradeId = QSR.Trade.UserTradeID, ChatId = QSR.Trade.UserID };
            //                    this.SaveMessageToLily(0, chatMessage);
            //                }
            //            }


            //            break;


            //        //case QuanYiServerBaseClass.DataTypeEnum.InitChatMessage:
            //        //    foreach (var r in Receivers)
            //        //    {
            //        //        lock (r)
            //        //        {
            //        //            QuanYiOrderServerResponseClass msgQsr = new QuanYiOrderServerResponseClass();
            //        //            msgQsr.UserID = QSR.UserID;
            //        //            msgQsr.SessionID = QSR.SessionID;
            //        //            msgQsr.BrokerID = r.BrokerID;
            //        //            msgQsr.DataType = QuanYiServerBaseClass.DataTypeEnum.ChatMessage;
            //        //            msgQsr.ChatImage = r.ChatMessage;
            //        //            serverWebSocketFromClient.SendResponseToClient(msgQsr);
            //        //        }
            //        //    }
            //        //    break;
            //        case QuanYiServerBaseClass.DataTypeEnum.ChatMessage:
            //            // 0代表普通消息，1代表下单的消息
            //            //快捷回复存到lily
            //            if ((QSR != null) && SendMessage(QSR, 0))
            //            {

            //                ChatMessage chatMessage = new ChatMessage() { BrokerId = QSR.BrokerID, ChatMessageInfo = QSR.ChatMessage, ChatId = QSR.UserID };
            //                this.SaveMessageToLily(0, chatMessage);
            //            }
            //            break;
            //        //ChatReceiver r1 = Receivers.Single(x => x.BrokerID == QSR.BrokerID);
            //        //if (r1 != null)
            //        //{
            //        //    UserTrade t = new UserTrade();
            //        //    t.Broker = r1.Broker;
            //        //    t.ChatID = r1.ChatID;
            //        //    t.Command = QSR.Message;
            //        //    t.ReceiverId = r1.id;
            //        //    SendMessage(t);
            //        //}
            //        //break;
            //        //case QuanYiServerBaseClass.DataTypeEnum.Deal:
            //        //    if (serverWebSocketFromClient.UserTradeDeal(QSR.Trade, out msg))
            //        //    {
            //        //        QSR.Code = 0;
            //        //    }
            //        //    else
            //        //    {
            //        //        QSR.Code = 1;

            //        //    }
            //        //    QSR.Message = msg;
            //        //    break;
            //        //default:
            //        //    break;
            //        case QuanYiServerBaseClass.DataTypeEnum.RequestReview:
            //            bool res = _dailyData.AddRequestReview(QSR);
            //            if (res)
            //            {
            //                AppLog.WriteInfo("插入一条新的复核" + QSR.RequestReviewMessage);
            //            }
            //            else
            //            {
            //                AppLog.WriteError("插入一条新的复核失败" + QSR.RequestReviewMessage);
            //            }
            //            break;
            //        default:
            //            break;
            //    }

            //    this.serverWebSocketFromClient?.SendResponseToClient(QSR);
            //    this.serverWebSocketFromAdmin?.SendMessageToAdmins(QSR);

            //}
            //catch (Exception ex)
            //{
            //    AppLog.WriteError(ex.Message + "QuanyiServer" + "Socket_QuanYiClientMessageEvent" + ex.StackTrace);
            //    //_dailyData.BondHelperSysLog(QSR.UserID, "客户端消息，" + ex.Message, QSR.Trade == null ? 0 : QSR.Trade.UserTradeID);
            //    QSR.Code = 7;
            //    QSR.Message = ex.Message;
            //    //serverWebSocketFromClient.SendResponseToClient(QSR);
            //}



        }
        #endregion

        #region 服务端——对接管理端服务
        public void StartAdminServerService()
        {
            serverWebSocketFromAdmin = new ServerWebSocketHelper(_dailyData);
            serverWebSocketFromAdmin.AdminMessageEvent += ServerWebSocketFromAdmin_AdminMessageEvent;
            serverWebSocketFromAdmin.QuanYiOrderServerMessageEvent += Websocket_QuanYiServerMessageEvent;
            serverWebSocketFromAdmin.adminWebSocketStart();
        }


        /// <summary>
        /// 收到管理端发给的服务端消息
        /// </summary>
        /// <param name="message"></param>
        /// <exception cref="NotImplementedException"></exception>
        private void ServerWebSocketFromAdmin_AdminMessageEvent(string message)
        {
            Growl.SuccessGlobal(message);
        }
        #endregion





        #region 辅助方法
        private string GetGreeting()
        {
            var hour = DateTime.Now.Hour;
            if (hour >= 6 && hour < 12)
            {
                return "早上好，";
            }
            else if (hour >= 12 && hour < 18)
            {
                return "中午好，";
            }
            else
            {
                return "晚上好，";
            }
        }

        private void Greet()
        {
            var greeting = GetGreeting();
            _eventAggregator.GetEvent<MessageEvent>().Publish(new MessageModel()
            {
                Filter = "1",
                Message = "登录成功。" + greeting + LoginViewModel.StaticUserName
            });
        }

        public void RefreshReceivers()
        {
            Receivers = _dailyData.GetChatReceivers();
        }


        /// <summary>
        /// 核心方法，找到窗口然后发送
        /// </summary>
        /// <param name="order"></param>
        private void SendMessage(UserTrade order)
        {

            IntPtr window = FindWindow(null, order.ChatID.Trim());
            //IntPtr TextWindows = IntPtr.Zero;
            //var prc = Process.GetProcessesByName("WeChat.exe");
            if (window != IntPtr.Zero)
            {
                lock (lockObject)
                {
                    //ShowWindow(window, SW_SHOWNORMAL);
                    //SetForegroundWindow(window);
                    Thread t = new Thread(() => SendMessageToTarget(order.Command,window));
                    t.SetApartmentState(ApartmentState.STA);
                    t.Start();
                    t.Join();
                }
                //TextWindows = FindTradeWindow(window);
            }
            else
            {
                AppLog.WriteError("未找到可以交易发送中介的窗口" + order.ToString());
                return;
            }

            //ChatReceiver chat = null;
            //try
            //{
            //    chat = Receivers.Single(x => x.Id == order.ReceiverId);
            //    if (chat == null)
            //    {
            //        _dailyData.BondHelperSysLog(order.UserID, "Cannot find target receiver", order.UserTradeID);
            //        return;
            //    }
            //}
            //catch (Exception ex)
            //{
            //    AppLog.WriteError(ex.Message + "PlaceOrderServer" + "SendMessage" + ex.StackTrace);
            //    return;
            //}

        }


        public List<Tuple<int, string>> clientSendMessages = new List<Tuple<int, string>>();//发送端缓存？？
        /// <summary>
        /// 核心方法，找到窗口然后发送
        /// </summary>
        /// <param name="order"></param>
        //private void SendMessage(QuanYiOrderServerResponseClass qsr)
        //{
        //    int brokerId = qsr.BrokerID;
        //    string chatMsg = qsr.ChatMessage;
        //    int userId = qsr.UserID;
        //    string brokerName = Receivers.Single(o => o.Brokerid == brokerId).ChatId;

        //    IntPtr window = FindWindow(null, brokerName);
        //    //IntPtr TextWindows = IntPtr.Zero;
        //    //var prc = Process.GetProcessesByName("WeChat.exe");
        //    if (window != IntPtr.Zero)
        //    {
        //        ShowWindow(window, SW_SHOWNORMAL);
        //        SetForegroundWindow(window);
        //        //TextWindows = FindTradeWindow(window);
        //    }
        //    else
        //    {
        //        AppLog.WriteError("未找到可以交易发送中介的窗口" + brokerName);
        //        return;
        //    }

        //    Task.Delay(100).Wait();
        //    this.ChatMessageLog += "中介名" + brokerName + "，消息：" + chatMsg + "\r\n";
        //    Thread t = new Thread(() => SendMessageToTarget(chatMsg));
        //    t.SetApartmentState(ApartmentState.STA);
        //    t.Start();
        //    t.Join();
        //}
        //[STAThread]
        //private void SendMessageToTarget(string msg)
        //{

        //    Clipboard.SetText(msg);

        //    SendKeys.SendWait("^v");
        //    Task.Delay(10).Wait();

        //    SendKeys.SendWait("{ENTER}");

        //}

        private async Task SendMessageTaskAsync(QuanYiOrderServerResponseClass qsr, int i = 0)
        {
            await semaphore.WaitAsync();
            try
            {
                DateTime startTime = DateTime.Now;
                AppLog.WriteInfo("任务B开始时间：" + startTime.ToString("yyyy/MM/dd HH:mm:ss.fff"));

                SendMessage(qsr, i);

                // 记录任务B结束时间
                DateTime endTime = DateTime.Now;
                AppLog.WriteInfo("任务B结束时间：" + endTime.ToString("yyyy/MM/dd HH:mm:ss.fff"));

                // 计算时间差
                TimeSpan elapsedTime = endTime - startTime;
                AppLog.WriteInfo(string.Format("任务B花费时间：{0} 毫秒", elapsedTime.TotalMilliseconds));
            }
            catch (Exception ex)
            {
                AppLog.WriteError("任务B异常：" + ex.Message);
            }
            finally
            {
                semaphore.Release();
            }
        }

        //bug修改，24/07/05 1代表下单，0代表普通,2代表 审核员（可以随意发送）
        private bool SendMessage(QuanYiOrderServerResponseClass qsr, int i = 0)
        {
            semaphore.Wait();
            try
            {
                lock (lockObject)
                {
                    if (i == 0)
                    {
                        int brokerId = qsr.BrokerID;
                        string chatMsg = qsr.ChatMessage;
                        int userId = qsr.UserID;
                        string brokerName = Receivers.Single(o => o.Brokerid == brokerId).ChatId;

                        IntPtr window = FindWindow(null, brokerName);
                        if (window != IntPtr.Zero)
                        {
                            Thread t = new Thread(() => SendMessageToTarget(chatMsg, window, brokerName));
                            t.SetApartmentState(ApartmentState.STA);
                            t.Start();
                            t.Join();
                            return true;

                        }
                        else
                        {
                            AppLog.WriteError($"i==0未找到{brokerName}的中介聊天框");
                            return false;
                            
                        }
                    }
                    else if(i==1) 
                    {
                        UserTrade order = qsr.Trade;
                        int? brokerId = order.BrokerID;
                        string brokerName = null;
                        if (brokerId.HasValue)
                        {
                            var receiver = Receivers.SingleOrDefault(o => o.Brokerid == brokerId.Value);
                            if (receiver != null)
                            {
                                 brokerName = receiver.ChatId;
                                // 使用 brokerName 进行其他操作
                            }
                            else
                            {
                                // 处理没有找到匹配项的情况
                                AppLog.WriteError("No matching broker found for brokerId: " + brokerId.Value);
                                return false;
                            }
                        }
                        else
                        {
                            // 处理 brokerId 为 null 的情况
                            AppLog.WriteError("brokerId is null.");
                            return false;
                        }
                        if (brokerName == null)
                        {
                            AppLog.WriteError("brokerName is null.");
                            return false;
                        }
                        IntPtr num = FindWindow(null, brokerName);
                        string message;
                        message = qsr?.Message;

                        if (num != IntPtr.Zero)
                        {

                            //ShowWindow(num, SW_SHOWNORMAL);
                            //SetForegroundWindow(num);

                            string log = "中介名" + brokerName + "，消息：" + message + "\r\n";
                            AppLog.WriteInfo("记录下单事件" + log);
                            try
                            {
                                //val = Receivers.Single((ChatReceiver x) => x.Id == order.ReceiverId);
                                //if (val == null)
                                //{
                                //    _dailyData.BondHelperSysLog(order.UserID, "Cannot find target receiver", order.UserTradeID);
                                //    return;
                                //}
                                Thread t = new Thread(() => SendMessageToTarget(message,num,brokerName));
                                t.SetApartmentState(ApartmentState.STA);
                                t.Start();
                                t.Join();
                                //Thread thread = new Thread((ThreadStart)delegate
                                //{
                                //    SendMessageToTarget(message);
                                //});
                                //thread.SetApartmentState(ApartmentState.STA);
                                //thread.Start();


                                //thread.Join();
                                return true;

                            }
                            catch (Exception ex)
                            {
                                AppLog.WriteError(ex.Message + "PlaceOrderServerSendMessage" + ex.StackTrace, "", true);
                                return false;
                            }

                        }
                        else
                        {
                            AppLog.WriteError($"没有找到名为{brokerName}的窗口!");
                            return false;
                        }
                    }
                    else
                    {
                        int brokerId = qsr.BrokerID;
                        string chatMsg = qsr.ChatMessage;
                        int userId = qsr.UserID;
                        string brokerName = Receivers.Single(o => o.Brokerid == brokerId).ChatId;

                        IntPtr window = FindWindow(null, brokerName);
                        if (window != IntPtr.Zero)
                        {
                            Thread t = new Thread(() => SendMessageToTarget(chatMsg, window, brokerName));
                            t.SetApartmentState(ApartmentState.STA);
                            t.Start();
                            t.Join();
                            return true;

                        }
                        else
                        {
                            AppLog.WriteError($"i==2 说明是审核员 未找到{brokerName}的中介聊天框");
                            return false;
                         
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                AppLog.WriteError($"SendMessage异常，{ex.StackTrace}---{ex.Message}");
                return false;
            }
            finally
            {
                Thread.Sleep(10);
                semaphore.Release();
            }

        }

        private readonly object clipboardLock = new object(); // 剪贴板锁对象
        [STAThread]
        private void SendMessageToTarget(string msg,IntPtr window, string brokerName=null)
        {
            try
            {
                if(string.IsNullOrEmpty(brokerName))
                {
                    AppLog.WriteError("中介名为空，异常");
                    return;
                }
                lock (clipboardLock)
                {
                    
                    AppLog.WriteInfo($"发送消息{msg},中介{brokerName}");
                    PrismApplication.Current.Dispatcher.Invoke(() =>
                    {
                        ShowWindow(window, SW_SHOWNORMAL);
                        SetForegroundWindow(window);

                        Thread.Sleep(50);

                        // 获取当前前景窗口的句柄
                        IntPtr currentForegroundWindow = GetForegroundWindow();
                        //Clipboard.SetText(msg);
                        // 获取前景窗口的标题
                        System.Text.StringBuilder windowText = new System.Text.StringBuilder(256);
                        GetWindowText(currentForegroundWindow, windowText, 256);
                        // 检查前景窗口是否为目标窗口
                        if (windowText.ToString().Contains(brokerName))
                        {
                            Clipboard.SetText(msg);

                            SendKeys.SendWait("^v");
                            Thread.Sleep(15);
                            SendKeys.SendWait("{ENTER}");
                            AppLog.WriteInfo($"找到是目标窗口{brokerName}的窗口，消息{msg}");
                        }
                        else
                        {
                            AppLog.WriteError($"当前最前窗口不是目标窗口{brokerName}。消息{msg}");
                        }
                        //SendKeys.SendWait("^v");
                        //SendKeys.SendWait("{ENTER}");
                    });
              
                
                }
            }
            catch (Exception ex)
            {
                AppLog.WriteError("SendMessageToTarget异常" + ex.Message + "！" + ex.StackTrace);
            }
        }

        [DllImport("user32.dll")]
        private static extern IntPtr GetForegroundWindow();
        [DllImport("user32.dll")]
        private static extern int GetWindowText(IntPtr hWnd, System.Text.StringBuilder text, int count);

        // 声明一个对象作为互斥锁[刷新和发送]
        private object lockObject = new object();
        #endregion

        #region win32API相关
        [DllImport("user32.dll")]
        public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

        [DllImport("user32.dll")]
        private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

        [DllImport("user32")]
        static extern int SetForegroundWindow(IntPtr hwnd);

        private const int SW_SHOWNORMAL = 1;
        #endregion



        #region 捕获消息服务
        List<string> ChatName = new List<string>();
        //public Dictionary<string, List<ChatMessage>> AllChatDictionary { get; private set; }//字典

        // 声明 ConcurrentDictionary提高性能
        private ConcurrentDictionary<string, List<ChatMessage>> AllChatDictionary = new ConcurrentDictionary<string, List<ChatMessage>>();

        //下单加入的字典
        private ConcurrentDictionary<string, ConcurrentBag<string>> OrderChatMessageDictionary = new ConcurrentDictionary<string, ConcurrentBag<string>>();

        private object lock1 = new object();
        private void StartCaptureMessageService()
        {
            try
            {
                AllChatDictionary = new ConcurrentDictionary<string, List<ChatMessage>>();
                Thread t = new Thread(new ThreadStart(CapturePoint));
                t.IsBackground = true;
                t.Start();
            }
            catch (Exception ex)
            {
                AppLog.WriteError("StartCaptureMessageService" + ex.Message + ex.StackTrace);
            }

        }

        private int timerSeconds;

        public int TimerSeconds
        {
            get { return timerSeconds; }
            set { timerSeconds = value; RaisePropertyChanged(); }
        }

        private void ModifyInterval()
        {
            if (timer != null && timer.Enabled)
            {
                timer.Interval = TimerSeconds * 1000;
                Growl.SuccessGlobal("定时器间隔修改为：" + TimerSeconds + " 秒");
            }
        }

        public System.Timers.Timer timer { get; set; }

        #region 同步方法

        //private void GetChatMessageFromWindow(string chatterName)
        //{
        //    try
        //    {
        //        IntPtr hWnd = Helper.WindowHelper.FindWindow(null, chatterName);
        //        if (hWnd == IntPtr.Zero)
        //        {
        //            hWnd = Helper.WindowHelper.FindWindow(null, Helper.WindowHelper.getAnotherTitle(chatterName));
        //            if (hWnd == IntPtr.Zero)
        //            {
        //                AppLog.WriteWarn($"未找到{chatterName}的窗口");
        //                return; // Window not found
        //            }
        //        }
        //        else
        //        {
        //            lock (lockObject) // 如果需要保护窗口操作，可以在这里加锁
        //            {
        //                ShowWindow(hWnd, SW_SHOWNORMAL);
        //                SetForegroundWindow(hWnd);
        //                SendKeys.SendWait("{ENTER}");
        //            }
        //            获取窗口左上角坐标
        //           Point windowPoint = Helper.WindowHelper.GetWindowTopLeftCorner("QiDian", chatterName);

        //            if (windowPoint.X == 0 && windowPoint.Y == 0 || windowPoint.X.ToString().Contains("-32000"))
        //            {
        //                AppLog.WriteInfo($"窗体 {chatterName} 在原点（0,0）");
        //                return;
        //                窗体在原点（0,0）
        //            }
        //            IntPtr handleQD = Helper.WindowHelper.WindowFromPoint(windowPoint);
        //            GetMessage(windowPoint, handleQD, chatterName);
        //        }
        //    }
        //    catch (System.Exception ex)
        //    {
        //        AppLog.WriteError($"{ex.Message} CheckMsgFromWindow for {chatterName}");
        //    }
        //}

        //private void ReceiveInfo()
        //{
        //    lock (lockObject)
        //    {
        //        foreach (var chatName in ChatName)
        //        {
        //            GetChatMessageFromWindow(chatName);
        //        }
        //    }
        //}

        private async void TestCatch()
        {
            //执行长时间任务
            await Task.Delay(2000);
            foreach (var chatName in ChatName)
            {
                GetChatMessageFromWindow(chatName);
            }
        }


        //private void CapturePoint()
        //{
        //    timer = new System.Timers.Timer();
        //    timer.Interval = 20000;
        //    timer.Enabled = true;
        //    timer.AutoReset = true; // 设置是执行一次（false）还是一直执行(true)
        //    timer.Elapsed += (o, a) =>
        //    {
        //        记录更新开始时间
        //       DateTime startTime = DateTime.Now;
        //        AppLog.WriteInfo("更新开始时间：" + startTime.ToString("yyyy/MM/dd HH:mm:ss.fff"));

        //        执行长时间任务
        //        ReceiveInfo();

        //        记录更新结束时间
        //       DateTime endTime = DateTime.Now;
        //        AppLog.WriteInfo("更新结束时间：" + endTime.ToString("yyyy/MM/dd HH:mm:ss.fff"));

        //        计算时间差
        //       TimeSpan elapsedTime = endTime - startTime;
        //        AppLog.WriteInfo(string.Format("更新花费时间：{0} 毫秒", elapsedTime.TotalMilliseconds));
        //    };

        //    timer.Start();
        //}

        #endregion



        #region 异步注释 24/07/17
        private void CapturePoint()
        {
            timer = new System.Timers.Timer();
            timer.Interval = 4000;
            timer.Enabled = true;
            timer.AutoReset = true;//设置是执行一次（false）还是一直执行(true)；  
            timer.Elapsed += (o, a) =>
            {
                 semaphore.Wait();
                // 记录更新开始时间
                try
                {
                    DateTime startTime = DateTime.Now;
                    AppLog.WriteInfo("更新开始时间：" + startTime.ToString("yyyy/MM/dd HH:mm:ss.fff"));

                    // 执行长时间任务
                    ReceiveInfo();

                    // 记录更新结束时间
                    DateTime endTime = DateTime.Now;
                    AppLog.WriteInfo("更新结束时间：" + endTime.ToString("yyyy/MM/dd HH:mm:ss.fff"));

                    // 计算时间差
                    TimeSpan elapsedTime = endTime - startTime;
                    AppLog.WriteInfo(string.Format("更新花费时间：{0} 毫秒", elapsedTime.TotalMilliseconds));
                }
                catch(Exception ex)
                {
                    AppLog.WriteError("CapturePoint异常" + ex.Message);
                }
                finally
                {
                    Thread.Sleep(10);
                    semaphore.Release();
                }
                
            };

            timer.Start();
        }
        private SemaphoreSlim semaphore = new SemaphoreSlim(1, 1);

        private void ReceiveInfo()
        {
            //await semaphore.WaitAsync();

            try
            {

                foreach (var chatName in ChatName)
                {
                    GetChatMessageFromWindow(chatName);
                }

                CheckIfIsLogOut();//检查是否被登出
            }
            catch (Exception ex)
            {
                AppLog.WriteError("ReceiveInfo异常" + ex.Message + ex.StackTrace);
            }
            finally
            {
                //semaphore.Release();
            }
        }
        
        int logOutCount = 0;

        //bool isResolved = false;
        private async void CheckIfIsLogOut()
        {
            
                IntPtr hWnd = Helper.WindowHelper.FindWindow(null, "下线通知");
                if (hWnd != IntPtr.Zero)
                {
                
                if (logOutCount%20==0)
                    {
                        string message = "QTRADE已下线，请紧急处理！";
                        AppLog.WriteError(message);
                        var notification = new WeChatNotificationClass
                        {
                            UserID = 107,
                            NickName = "邪恶心机炜",
                            TotalProfit = 1000,
                            Message = message,
                           
                        };
                        await WeChatService.SendWeChatNotificationAsync(notification);

                    this.SendQTradeNotOpen();
                    }
                logOutCount++;
            }
            
        }


        private async void SendMessageToWechat(string message)
        {
            
                    //AppLog.WriteError(message);
                    var notification = new WeChatNotificationClass
                    {
                        UserID = 107,
                        NickName = "邪恶心机炜",
                        TotalProfit = 1000,
                        Message = message,
                    };
                    await WeChatService.SendWeChatNotificationAsync(notification);
            

        }
        private async Task ReceiveInfoAsync()
        {
            //await semaphore.WaitAsync();

            try
            {

                foreach (var chatName in ChatName)
                {
                   await GetChatMessageFromWindowAsync(chatName);
                }
            }
            catch (Exception ex)
            {
                AppLog.WriteError("ReceiveInfoAsync异常" + ex.Message + ex.StackTrace);
            }
            finally
            {
                //semaphore.Release();
            }
        }

        public int count = 0;

        private static readonly Dictionary<string, DateTime> lastSentTimes = new Dictionary<string, DateTime>();
        private static readonly TimeSpan SendInterval = TimeSpan.FromMinutes(1); // 控制发送间隔为1分钟
        private void GetChatMessageFromWindow(string chatterName)
        {
            try
            {
                lock (lockObject)
                {
                    IntPtr hWnd = Helper.WindowHelper.FindWindow(null, chatterName);
                    if (hWnd == IntPtr.Zero)
                    {
                        DateTime now = DateTime.Now;
                        if (!lastSentTimes.TryGetValue(chatterName, out DateTime lastSentTime) || (now - lastSentTime) > SendInterval)
                        {
                            string msg = $"未找到中介{chatterName}的窗口,请处理！时间：{now}";
                            AppLog.WriteError(msg);
                            SendMessageToWechat(msg);
                            lastSentTimes[chatterName] = now; // 更新指定的 chatterName 的上次发送时间
                        }
                        return;
                    }
                    else
                    {

                        ShowWindow(hWnd, SW_SHOWNORMAL);
                        SetForegroundWindow(hWnd);
                        SendKeys.SendWait("{ENTER}");
                        //lock (lockObject) // 如果需要保护窗口操作，可以在这里加锁
                        //{
                        //    ShowWindow(hWnd, SW_SHOWNORMAL);
                        //    SetForegroundWindow(hWnd);
                        //    SendKeys.SendWait("{ENTER}");
                        //}

                        PrismApplication.Current.Dispatcher.Invoke(() =>
                        {
                            ShowWindow(hWnd, SW_SHOWNORMAL);
                            SetForegroundWindow(hWnd);
                            Thread.Sleep(20);
                            SendKeys.SendWait("{ENTER}");
                        });
                
                        // 异步获取窗口左上角坐标
                        Point windowPoint = Helper.WindowHelper.GetWindowTopLeftCorner("QiDian", chatterName);

                        if (windowPoint.X <= 0 && windowPoint.Y <= 0 || windowPoint.X.ToString().Contains("-32000"))
                        {
                            AppLog.WriteInfo($"窗体 {chatterName} 在原点（0,0）");
                            return;
                            // 窗体在原点（0,0）
                        }
                        IntPtr handleQD = Helper.WindowHelper.WindowFromPoint(windowPoint);

                        // 确保 handleQD 是有效的
                        if (handleQD == IntPtr.Zero)
                        {
                            AppLog.WriteError($"{chatterName} 在 ({windowPoint.X}, {windowPoint.Y}) 未找到有效窗口");
                            return;
                        }
                        GetMessage(windowPoint, handleQD, chatterName);
                    }
                }

            }
            catch (System.Exception ex)
            {
                AppLog.WriteError($"{ex.Message}--{ex.StackTrace} GetChatMessageFromWindow for {chatterName}");
            }
        }
        private async Task GetChatMessageFromWindowAsync(string chatterName)
        {
            try
            {
                lock (lockObject)
                {
                    IntPtr hWnd = Helper.WindowHelper.FindWindow(null, chatterName);
                    if (hWnd == IntPtr.Zero)
                    {
                        hWnd = Helper.WindowHelper.FindWindow(null, Helper.WindowHelper.getAnotherTitle(chatterName));
                        if (hWnd == IntPtr.Zero)
                        {
                            //AppLog.WriteWarn($"未找到{chatterName}的窗口");
                            return; // Window not found
                        }
                    }
                    else
                    {
                        //lock (lockObject) // 如果需要保护窗口操作，可以在这里加锁
                        //{
                        //    ShowWindow(hWnd, SW_SHOWNORMAL);
                        //    SetForegroundWindow(hWnd);
                        //    SendKeys.SendWait("{ENTER}");
                        //}

                        PrismApplication.Current.Dispatcher.Invoke(() =>
                        {
                            ShowWindow(hWnd, SW_SHOWNORMAL);
                            Thread.Sleep(10);
                            SetForegroundWindow(hWnd);
                            Thread.Sleep(10);
                            SendKeys.SendWait("{ENTER}");
                        });
                        // 异步获取窗口左上角坐标
                        Point windowPoint = Helper.WindowHelper.GetWindowTopLeftCorner("QiDian", chatterName);

                        if (windowPoint.X == 0 && windowPoint.Y == 0 || windowPoint.X.ToString().Contains("-32000"))
                        {
                            AppLog.WriteInfo($"窗体 {chatterName} 在原点（0,0）");
                            return;
                            // 窗体在原点（0,0）
                        }
                        IntPtr handleQD = Helper.WindowHelper.WindowFromPoint(windowPoint);
                        GetMessage(windowPoint, handleQD, chatterName);
                    }
                }

            }
            catch (Exception ex)
            {
                AppLog.WriteError($"{ex.Message} CheckMsgFromWindow for {chatterName}");
            }
        }
        #endregion
        //窗口相关参数（都是以窗口左上角那点为基准）
        private int leftPoint = 470;
        private int downPoint = 170;
        private int step = 6; // 步长（上下）
        private int windowHeight = 390;//只是聊天窗体的高度
        private string GetMessage(Point windowPoint, IntPtr hwnd, string chatName)
        {
            try
            {
                //AppLog.WriteInfo($"{chatName}--窗体左上角为：x:{windowPoint.X},y:{windowPoint.Y}！");


             
                    lock (lockObject)
                    {

                        string clipboardContent = null;

                        int sendMessageCount = 0;
                        int receiveMessageCount = 0;
                        int searchStartX = windowPoint.X + leftPoint; 
                        int searchStartY = windowPoint.Y + downPoint; 
                                                                      

                        var sim = new InputSimulator();
                        // 将屏幕坐标转换为虚拟桌面坐标
                        int virtualScreenX = searchStartX * 65535 / Screen.PrimaryScreen.Bounds.Width;
                        int virtualScreenY = searchStartY * 65535 / Screen.PrimaryScreen.Bounds.Height;

                        // 模拟点击获取焦点
                        sim.Mouse.MoveMouseToPositionOnVirtualDesktop(virtualScreenX, virtualScreenY);
                        sim.Mouse.LeftButtonClick();

                        // 等待点击操作完成
                        Thread.Sleep(10);

                        // 模拟 Ctrl + A 全选
                        sim.Keyboard.ModifiedKeyStroke(VirtualKeyCode.CONTROL, VirtualKeyCode.VK_A);

                        // 等待全选操作完成
                        Thread.Sleep(10);

                        // 模拟 Ctrl + C 复制
                        sim.Keyboard.ModifiedKeyStroke(VirtualKeyCode.CONTROL, VirtualKeyCode.VK_C);

                        // 等待复制操作完成
                        Thread.Sleep(10);

                        // 再次点击取消焦点
                        sim.Mouse.LeftButtonClick();
                        //Thread.Sleep(200);

                        Thread staThread = new Thread(
                                       delegate ()
                                       {
                                           try
                                           {
                                               // 确保线程在 STA 模式下运行
                                               if (Thread.CurrentThread.GetApartmentState() != ApartmentState.STA)
                                               {
                                                   AppLog.WriteError("必须要是STA线程执行啊!");
                                                   //throw new ThreadStateException("The thread must be in STA mode to access the clipboard.");
                                                   return;
                                               }

                                               // 获取剪贴板的文本内容
                                               clipboardContent = Clipboard.GetText();
                                               if(string.IsNullOrEmpty(clipboardContent))
                                               {
                                                   return;
                                               }
                                               var ParsedMessage = ParseMessages(clipboardContent);

                                               if (!AllChatDictionary.ContainsKey(chatName))
                                               {

                                                   UpdateMessages(chatName, ParsedMessage);
                                               }
                                               else
                                               {
                                                   UpdateMessages(chatName, ParsedMessage);
                                               }
                                           }

                                           catch (Exception ex)
                                           {

                                           }
                                       });
                        staThread.SetApartmentState(ApartmentState.STA);
                        staThread.Start();
                        staThread.Join();
                    }
                
             
           
                // 写入文件
                //string fileName = $"{chatName}.txt"; // 文件名为 chatName.txt
                //string filePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), fileName); // 保存在桌面上

                //using (StreamWriter writer = new StreamWriter(filePath, false)) // false 表示覆盖已存在的文件，true 表示追加到文件末尾
                //{
                //    writer.Write(clipboardContent);
                //}


                //AppLog.WriteInfo("聊天人" + chatName + $"共找到{sendMessageCount}个发送方聊天气泡");





                return "1";
            }
            catch (Exception ex)
            {
                AppLog.WriteError("聊天人" + chatName + ex.Message + "抓取文本异常");
            }
            finally
            {

            }
            return null;
        }


        /// <summary>
        /// 更改逻辑，对接李浩240706
        /// </summary>
        /// <param name="chatName"></param>
        /// <param name="parsedMessages"></param>
        //private void UpdateMessages(string chatName, List<ChatMessage> parsedMessages)
        //{
        //    try
        //    {
        //        ///说明重开程序了
        //        if (parsedMessages == null || !parsedMessages.Any())
        //        {
        //            AppLog.WriteError($"parsedMessages 为空或无消息。清空{chatName}");
        //            if (AllChatDictionary.ContainsKey(chatName))
        //            {
        //                AllChatDictionary[chatName].Clear();
        //                AllChatDictionary.Remove(chatName);
        //            }
        //            else
        //            {
        //                AllChatDictionary.Remove(chatName);
        //            }
        //            return;
        //        }

        //        int brokerId = Receivers.Where(o => o.ChatId == chatName).FirstOrDefault()?.Brokerid ?? 0;
        //        if (brokerId == 0)
        //        {
        //            AppLog.WriteError($"无法找到与聊天名称 '{chatName}' 相关的经纪人ID.");
        //            return;
        //        }

        //        if (!AllChatDictionary.ContainsKey(chatName))
        //        {
        //            // Step 1: 查询数据库中已有的消息
        //            var existingMessages = GetRecentMessagesFromDatabase(brokerId);


        //            // Step 2:获取 parsedMessages 的最小和最大时间
        //            var parsedMinTime = parsedMessages.First().CreateTime;
        //            var parsedMaxTime = parsedMessages.Last().CreateTime;


        //            // 获取数据库中最大时间
        //            var databaseMaxTime = existingMessages.Max(m => m.CreateTime);

        //            if (parsedMinTime > databaseMaxTime)
        //            {
        //                foreach (var item in parsedMessages)
        //                {
        //                    if (item.Direction == 0)
        //                    {
        //                        this.SaveMessages(0, item);
        //                    }
        //                    else
        //                    {
        //                        this.SaveMessages(1, item);
        //                    }
        //                    AppLog.WriteWarn("捕捉到新数据" + chatName + item.ChatMessageInfo);
        //                    this.ChatMessageLog += "名称" + chatName + "，消息：" + item.ChatMessageInfo + "\r\n";

        //                }
        //            }
        //            else if (parsedMaxTime <= databaseMaxTime)
        //            {
        //                // 如果解析的消息最大时间都比数据库最大时间小，说明数据库中已经有这些消息，无需操作
        //                return;
        //            }
        //            else
        //            {
        //                // 找出需要增量插入的消息（即时间大于数据库最大时间的消息）
        //                var newMessages = parsedMessages.Where(m => m.CreateTime > databaseMaxTime).ToList();
        //                if (newMessages.Count > 0)
        //                {
        //                    foreach (var item in newMessages)
        //                    {
        //                        if (item.Direction == 0)
        //                        {
        //                            this.SaveMessages(0, item);
        //                        }else
        //                        {
        //                            this.SaveMessages(1, item);
        //                        }
        //                        AppLog.WriteWarn("捕捉到新数据" + chatName + item.ChatMessageInfo);
        //                        this.ChatMessageLog += "名称" + chatName + "，消息：" + item.ChatMessageInfo + "\r\n";

        //                    }
        //                }
        //            }

        //            AllChatDictionary[chatName] = parsedMessages;
        //            return;
        //        }

        //        // 获取当前存储的消息列表
        //        List<ChatMessage> currentMessages = AllChatDictionary[chatName];

        //        if (currentMessages.Any())
        //        {

        //            if (parsedMessages==null|| currentMessages.Count()>parsedMessages.Count())
        //            {
        //                AppLog.WriteError($"解析的大于当前字典的内容，说明删除过聊天记录了");
        //                if (AllChatDictionary.ContainsKey(chatName))
        //                {
        //                    AllChatDictionary[chatName].Clear();
        //                    AllChatDictionary.Remove(chatName);
        //                }
        //                else
        //                {
        //                    AllChatDictionary.Remove(chatName);
        //                }
        //                return;
        //            }

        //            // 找到 currentMessages 中最后一条消息的时间戳
        //            DateTime lastMessageTime = (DateTime)(currentMessages.Last()?.CreateTime);

        //            // 找到在 parsedMessages 中第一个大于 lastMessageTime 的消息索引
        //            int newMessageStartIndex = 0;
        //            for (int i = 0; i < parsedMessages.Count; i++)
        //            {
        //                if (parsedMessages[i].CreateTime > lastMessageTime)
        //                {
        //                    newMessageStartIndex = i;
        //                    break;
        //                }
        //            }

        //            if (newMessageStartIndex == 0)//说明找不到
        //            {
        //                newMessageStartIndex = currentMessages.Count;
        //            }
        //            // 获取新的消息列表
        //            List<ChatMessage> newMessages = parsedMessages.Skip(newMessageStartIndex).ToList();

        //            // 处理新消息逻辑
        //            if (newMessages.Any())
        //            {
        //                AppLog.WriteWarn($"捕捉到{newMessages.Count}条新数据");
        //                foreach (var item in newMessages)
        //                {
        //                    AppLog.WriteWarn("捕捉到新数据" + item.ChatMessageInfo);
        //                    this.ChatMessageLog += "名称" + chatName + "，消息：" + item.ChatMessageInfo + "\r\n";

        //                }
        //                // 插入新消息到数据库
        //                _dailyData.AddChatMessageList(brokerId, newMessages);

        //                // 更新 currentMessages 列表
        //                //currentMessages.AddRange(newMessages);
        //                AllChatDictionary[chatName] = parsedMessages;

        //                // 发送 WebSocket 消息给客户端和管理员
        //                SendWebSocketToClientsAndAdmins(brokerId, newMessages);
        //            }
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        AppLog.WriteError($"更新消息时发生异常: {ex.Message}");
        //        // 可以选择在这里处理异常，例如记录日志或者通知用户
        //    }
        //}
        // 修改 UpdateMessages 方法
        private void UpdateMessages(string chatName, List<ChatMessage> parsedMessages)
        {
            try
            {
                // 说明重开程序了
                if (parsedMessages == null || !parsedMessages.Any())
                {
                    //AppLog.WriteError($"parsedMessages 为空或无消息。清空{chatName}");
                    AllChatDictionary.TryRemove(chatName, out _);
                    return;
                }

                int brokerId = Receivers.Where(o => o.ChatId == chatName).FirstOrDefault()?.Brokerid ?? 0;
                if (brokerId == 0)
                {
                    AppLog.WriteError($"无法找到与聊天名称 '{chatName}' 相关的经纪人ID.");
                    return;
                }

                if (!AllChatDictionary.ContainsKey(chatName))
                {
                    // Step 1: 查询数据库中已有的消息
                    var existingMessages = GetRecentMessagesFromDatabase(brokerId);

                    // Step 2:获取 parsedMessages 的最小和最大时间
                    var parsedMinTime = parsedMessages.First().CreateTime;
                    var parsedMaxTime = parsedMessages.Last().CreateTime;

                    // 获取数据库中最大时间
                    var databaseMaxTime = existingMessages.Max(m => m.CreateTime);

                    if (parsedMinTime > databaseMaxTime)
                    {
                        foreach (var item in parsedMessages)
                        {
                      
                            short direction = item.Direction.GetValueOrDefault();

                            if (direction == 1 && item.BrokerName == chatName) //只保存中介消息
                            {
                                item.BrokerId = brokerId;
                                SaveMessageToLily(direction, item);
                            }

                            AppLog.WriteInfo($"捕捉到新数据 {chatName} {item.ChatMessageInfo}");
                            //ChatMessageLog += $"名称 {chatName}，消息：{item.ChatMessageInfo}\r\n";
                        }
                    }
                    else if (parsedMaxTime <= databaseMaxTime)
                    {
                        // 如果解析的消息最大时间都比数据库最大时间小，说明数据库中已经有这些消息，无需操作
                        return;
                    }
                    else
                    {
                        // 找出需要增量插入的消息（即时间大于数据库最大时间的消息）
                        var newMessages = parsedMessages.Where(m => m.CreateTime > databaseMaxTime).ToList();
                        if (newMessages.Count > 0)
                        {
                            foreach (var item in newMessages)
                            {

                                short direction = item.Direction.GetValueOrDefault();
                                if (direction == 1 && item.BrokerName == chatName) //只保存中介消息
                                {
                                    item.BrokerId = brokerId;
                                    SaveMessageToLily(direction, item);
                                }
                                AppLog.WriteInfo($"捕捉到新数据 {chatName} {item.ChatMessageInfo}");
                                //ChatMessageLog += $"名称 {chatName}，消息：{item.ChatMessageInfo}\r\n";
                            }
                        }
                    }
                    AllChatDictionary.TryAdd(chatName, parsedMessages);
                    return;
                }

                // 获取当前存储的消息列表
                if (AllChatDictionary.TryGetValue(chatName, out List<ChatMessage> currentMessages))
                {
                    if (parsedMessages == null || currentMessages.Count() > parsedMessages.Count())
                    {
                        AppLog.WriteError($"解析的大于当前字典的内容，说明删除过聊天记录了");
                        AllChatDictionary.TryRemove(chatName, out _);
                        return;
                    }

                    // 找到 currentMessages 中最后一条消息的时间戳
                    DateTime lastMessageTime = (DateTime)currentMessages.Last().CreateTime;

                    // 找到在 parsedMessages 中第一个大于 lastMessageTime 的消息索引
                    int newMessageStartIndex = 0;
                    for (int i = 0; i < parsedMessages.Count; i++)
                    {
                        if (parsedMessages[i].CreateTime > lastMessageTime)
                        {
                            newMessageStartIndex = i;
                            break;
                        }
                    }

                    if (newMessageStartIndex == 0)
                    {
                        newMessageStartIndex = currentMessages.Count;
                    }

                    // 获取新的消息列表
                    List<ChatMessage> newMessages = parsedMessages.Skip(newMessageStartIndex).ToList();

                    // 处理新消息逻辑
                    if (newMessages.Any())
                    {
                        AppLog.WriteInfo($"捕捉到{newMessages.Count}条新数据");
                        foreach (var item in newMessages)
                        {
                            string msg = item.ChatMessageInfo;
                            bool found = false;
                            foreach (var kvp in OrderChatMessageDictionary)
                            {
                                ConcurrentBag<string> messages = kvp.Value;


                                if (messages.Contains(msg))
                                {
                                    found = true;
                                    break; // 找到后退出循环
                                }
                                //lock (messages) // 锁定列表以确保线程安全
                                //{
                                //    if (messages.Contains(msg))
                                //    {
                                //        found = true;
                                //        break; // 找到后退出循环
                                //    }
                                //}
                            }
                            // 根据是否找到消息来打印日志
                            if (found)
                            {
                                AppLog.WriteInfo($"找到了在 '{chatName}' 的消息: {msg}");
                            }
                            else
                            {
                                AppLog.WriteInfo($"这是啥？捕捉到新数据:'{chatName}'--- {msg}");
                            }
                            short direction = item.Direction.GetValueOrDefault();

                            if (direction == 1 && item.BrokerName == chatName) //只保存中介消息
                            {
                                item.BrokerId = brokerId;
                                SaveMessageToLily(direction, item);
                            }
                            //AppLog.WriteWarn($"捕捉到新数据 {chatName} {item.ChatMessageInfo}");
                            //ChatMessageLog += $"名称 {chatName}，消息：{item.ChatMessageInfo}\r\n";
                            AppLog.WriteInfo($"捕捉到新数据 {item.ChatMessageInfo}");
                            //ChatMessageLog += $"名称 {chatName}，消息：{item.ChatMessageInfo}\r\n";
                        }

                        // 插入新消息到数据库
                        //_dailyData.AddChatMessageList(brokerId, newMessages);

                        // 更新 currentMessages 列表
                        AllChatDictionary.TryUpdate(chatName, parsedMessages, currentMessages);

                        // 发送 WebSocket 消息给客户端和管理员
                        //SendWebSocketToClientsAndAdmins(brokerId, newMessages);
                    }
                }
            }
            catch (Exception ex)
            {
                AppLog.WriteError($"更新消息时发生异常: {ex.Message}");
                // 可以选择在这里处理异常，例如记录日志或者通知用户
            }
        }



        /// <summary>
        /// 增量式查找（默认找到最近连续的五条消息就说明到头了）然后可以对新增的进行插入操作
        /// </summary>
        /// <param name="chatName"></param>
        /// <param name="parsedMessage"></param>
        /// <exception cref="NotImplementedException"></exception>
        /// 
        //private void UpdateMessages(string chatName, List<ChatMessage> parsedMessages)
        //{
        //    try
        //    {
        //        ///说明重开程序了
        //        if (parsedMessages == null || !parsedMessages.Any())
        //        {
        //            AppLog.WriteError($"parsedMessages 为空或无消息。清空{chatName}");
        //            if (AllChatDictionary.ContainsKey(chatName))
        //            {
        //                AllChatDictionary[chatName].Clear();
        //                AllChatDictionary.Remove(chatName);
        //            }
        //            else
        //            {
        //                AllChatDictionary.Remove(chatName);
        //            }
        //            return;
        //        }

        //        int brokerId = Receivers.Where(o => o.ChatId == chatName).FirstOrDefault()?.Brokerid ?? 0;
        //        if (brokerId == 0)
        //        {
        //            AppLog.WriteError($"无法找到与聊天名称 '{chatName}' 相关的经纪人ID.");
        //            return;
        //        }

        //        if (!AllChatDictionary.ContainsKey(chatName))
        //        {
        //            // Step 1: 查询数据库中已有的消息
        //            var existingMessages = GetRecentMessagesFromDatabase(brokerId);
        //            // Step 2: 使用HashSet或Dictionary存储已有消息
        //            //var existingMessagesSet = new HashSet<(string ChatMessage, DateTime? Time)>(existingMessages
        //            //    .Select(em => (em.ChatMessageInfo.Replace("\r", ""), em.CreateTime)));
        //            var processedMessages = existingMessages
        //              .Select(em => (ChatMessage: em.ChatMessageInfo.Replace("\r", ""), Time: em.CreateTime))
        //              .ToList();
        //            // 第二步：处理消息内容，但不去重

        //            // Step 3: 确定时间范围
        //            var startTime = parsedMessages.First().CreateTime;
        //            var endTime = parsedMessages.Last().CreateTime;

        //            // Step 4: 删除时间范围内的消息
        //            //DeleteMessagesFromDatabase(brokerId, startTime, endTime);
        //            AppLog.WriteInfo($"删除{startTime}至{endTime}的db数据");
        //            // Step 4: 检查新消息并找出未存在的消息
        //            //var newChatMessages = new List<ChatMessage>();
        //            //foreach (var parsedMessage in parsedMessages)
        //            //{
        //            //    var key = (parsedMessage.ChatMessageInfo, parsedMessage.CreateTime);
        //            //    if (!processedMessages.Contains(key))
        //            //    {
        //            //        newChatMessages.Add(parsedMessage);
        //            //    }
        //            //}

        //            // Step 4: 批量插入新数据
        //            if (parsedMessages.Any())
        //            {
        //                AppLog.WriteWarn($"捕捉到{parsedMessages.Count}条新数据");
        //                foreach (var item in parsedMessages)
        //                {
        //                    if(item.Direction==0)
        //                    {
        //                        this.SaveMessages(0, item);
        //                    }
        //                    AppLog.WriteWarn("捕捉到新数据" + chatName + item.ChatMessageInfo);
        //                    this.ChatMessageLog += "名称" + chatName + "，消息：" + item.ChatMessageInfo + "\r\n";

        //                }


        //                //_dailyData.AddChatMessageList(brokerId, parsedMessages); 改成调李浩接口

        //                //web通过socket发送给管理端和客户端更新数据
        //                SendWebSocketToClientsAndAdmins(brokerId, parsedMessages);
        //            }
        //            AllChatDictionary[chatName] = parsedMessages;
        //            return;
        //        }

        //        // 获取当前存储的消息列表
        //        List<ChatMessage> currentMessages = AllChatDictionary[chatName];
        //        // 确保 currentMessages 至少有一条消息(重开了可能）
        //        //if(parsedMessages==null||parsedMessages.Count<=currentMessages.Count)
        //        //{
        //        //    if (AllChatDictionary.ContainsKey(chatName))
        //        //    {
        //        //        AllChatDictionary[chatName].Clear();
        //        //        AllChatDictionary.Remove(chatName);
        //        //    }
        //        //    else
        //        //    {
        //        //        AllChatDictionary.Remove(chatName);
        //        //    }
        //        //    //说明没有新消息
        //        //    return;
        //        //}

        //        if (currentMessages.Any())
        //        {
        //            // 找到 currentMessages 中最后一条消息的时间戳
        //            DateTime lastMessageTime = (DateTime)(currentMessages.Last()?.CreateTime);

        //            // 找到在 parsedMessages 中第一个大于 lastMessageTime 的消息索引
        //            int newMessageStartIndex = 0;
        //            for (int i = 0; i < parsedMessages.Count; i++)
        //            {
        //                if (parsedMessages[i].CreateTime > lastMessageTime)
        //                {
        //                    newMessageStartIndex = i;
        //                    break;
        //                }
        //            }

        //            if (newMessageStartIndex == 0)//说明找不到
        //            {
        //                newMessageStartIndex = currentMessages.Count;
        //            }
        //            // 获取新的消息列表
        //            List<ChatMessage> newMessages = parsedMessages.Skip(newMessageStartIndex).ToList();

        //            // 处理新消息逻辑
        //            if (newMessages.Any())
        //            {
        //                AppLog.WriteWarn($"捕捉到{newMessages.Count}条新数据");
        //                foreach (var item in newMessages)
        //                {
        //                    AppLog.WriteWarn("捕捉到新数据" + item.ChatMessageInfo);
        //                    this.ChatMessageLog += "名称" + chatName + "，消息：" + item.ChatMessageInfo + "\r\n";

        //                }
        //                // 插入新消息到数据库
        //                _dailyData.AddChatMessageList(brokerId, newMessages);

        //                // 更新 currentMessages 列表
        //                //currentMessages.AddRange(newMessages);
        //                AllChatDictionary[chatName] = parsedMessages;

        //                // 发送 WebSocket 消息给客户端和管理员
        //                SendWebSocketToClientsAndAdmins(brokerId, newMessages);
        //            }
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        AppLog.WriteError($"更新消息时发生异常: {ex.Message}");
        //        // 可以选择在这里处理异常，例如记录日志或者通知用户
        //    }
        //}

        private void DeleteMessagesFromDatabase(int brokerId, DateTime? startTime, DateTime? endTime)
        {
            try
            {
                _dailyData.DelChatMessageListByCreateTime(brokerId, startTime, endTime);
            }
            catch (Exception ex)
            {
                AppLog.WriteError(ex.Message + ex.StackTrace + "异常：DeleteMessagesFromDatabase");
            }
        }

        //private void UpdateMessages(string chatName, List<ChatMessage> parsedMessages)
        //{
        //    int brokerId = (int)Receivers.Where(o => o.ChatId == chatName).FirstOrDefault().Brokerid;
        //    if (!AllChatDictionary.ContainsKey(chatName))
        //    {
        //        // Step 1: 查询数据库中已有的消息
        //        var existingMessages = GetRecentMessagesFromDatabase(brokerId);
        //        // Step 2: 使用HashSet或Dictionary存储已有消息
        //        var existingMessagesSet = new HashSet<(string ChatMessage, DateTime? Time)>(existingMessages
        //            .Select(em => (em.ChatMessageInfo, em.CreateTime)));

        //        // Step 3: 检查新消息并找出未存在的消息
        //        var newChatMessages = new List<ChatMessage>();
        //        foreach (var parsedMessage in parsedMessages)
        //        {
        //            var key = (parsedMessage.ChatMessageInfo, parsedMessage.CreateTime);
        //            if (!existingMessagesSet.Contains(key))
        //            {
        //                newChatMessages.Add(parsedMessage);
        //            }
        //        }

        //        // Step 4: 批量插入新数据
        //        if (newChatMessages.Any())
        //        {
        //            AppLog.WriteWarn($"捕捉到{newChatMessages.Count}条新数据");
        //            foreach (var item in newChatMessages)
        //            {
        //                AppLog.WriteWarn("捕捉到新数据" + item.ChatMessageInfo);
        //            }
        //            _dailyData.AddChatMessageList(brokerId, newChatMessages);


        //            //web通过socket发送给管理端和客户端更新数据
        //            SendWebSocketToClientsAndAdmins(brokerId,newChatMessages);
        //        }
        //        AllChatDictionary[chatName] = parsedMessages;
        //        return;
        //    }

        //    // 获取当前存储的消息列表

        //    List<ChatMessage> currentMessages = AllChatDictionary[chatName];
        //    // 确保 currentMessages 至少有一条消息
        //    if (currentMessages.Any())
        //    {
        //        // 找到 currentMessages 中最后一条消息的时间戳
        //        DateTime lastMessageTime = (DateTime)(currentMessages.Last()?.CreateTime);

        //        // 找到在 parsedMessages 中第一个大于 lastMessageTime 的消息索引
        //        int newMessageStartIndex = 0;
        //        for (int i = 0; i < parsedMessages.Count; i++)
        //        {
        //            if (parsedMessages[i].CreateTime > lastMessageTime)
        //            {
        //                newMessageStartIndex = i;
        //                break;
        //            }
        //        }

        //        if(newMessageStartIndex==0)//说明找不到
        //        {
        //            newMessageStartIndex = currentMessages.Count;
        //        }
        //        // 获取新的消息列表
        //        List<ChatMessage> newMessages = parsedMessages.Skip(newMessageStartIndex).ToList();

        //        // 处理新消息逻辑
        //        if (newMessages.Any())
        //        {
        //            AppLog.WriteWarn($"捕捉到{newMessages.Count}条新数据");
        //            foreach (var item in newMessages)
        //            {
        //                AppLog.WriteWarn("捕捉到新数据" + item.ChatMessageInfo);
        //            }
        //            // 插入新消息到数据库
        //            _dailyData.AddChatMessageList(brokerId, newMessages);

        //            // 更新 currentMessages 列表
        //            //currentMessages.AddRange(newMessages);
        //            AllChatDictionary[chatName] = parsedMessages;

        //            // 发送 WebSocket 消息给客户端和管理员
        //            SendWebSocketToClientsAndAdmins(brokerId, newMessages);
        //        }
        //    }

        //    //// Get new messages to insert
        //    //List<ChatMessage> newMessages = parsedMessages.Skip(newMessageStartIndex).ToList();

        //    //if (newMessages.Any())
        //    //{
        //    //    // Insert new messages to database
        //    //    InsertNewMessagesToDatabase(chatName, newMessages);

        //    //    // Update current messages list
        //    //    currentMessages.AddRange(newMessages);
        //    //    AllChatDictionary[chatName] = currentMessages;

        //    //    // Optional: Send messages through WebSocket
        //    //    SendWebSocketToClientsAndAdmins(brokerId, newMessages);
        //    //}
        //}

        /// <summary>
        /// 把消息广播出去
        /// </summary>
        /// <param name="brokerId"></param>
        /// <param name="newChatMessages"></param>
        /// <exception cref="NotImplementedException"></exception>
        private void SendWebSocketToClientsAndAdmins(int brokerId, List<ChatMessage> newChatMessages)
        {
            //web通过socket发送给管理端和客户端
            try
            {
                QuanYiOrderServerResponseClass QSR = new QuanYiOrderServerResponseClass();
                QSR.DataType = QuanYiServerBaseClass.DataTypeEnum.NewChatMessageIn;
                QSR.NewChatMessageList = newChatMessages;
                this.serverWebSocketFromAdmin?.SendMessageToAdmins(QSR);
                this.serverWebSocketFromClient?.SendMessageToClients(QSR);
            }
            catch (Exception ex)
            {
                AppLog.WriteError("SendWebSocketToClientsAndAdmins异常" + ex.Message);
            }

        }

        private void InsertNewMessagesToDatabase(string chatName, List<ChatMessage> newMessages)
        {
            //db.ChatMessages.AddRange(newMessages);
            //db.SaveChanges();
        }
        /// <summary>
        /// 初始化消息方法，找到变化的
        /// </summary>
        /// <param name="chatName"></param>
        private void InitializeMessages(string chatName)
        {
            //if (!AllChatDictionary.ContainsKey(chatName))
            //{
            //    List<Message> initialMessages = db.ChatMessages
            //        .Where(o => o.ChatName == chatName)
            //        .OrderBy(a => a.CreateTime)
            //        .ToList();

            //    AllChatDictionary[chatName] = initialMessages;
            //}
        }


        /// <summary>
        /// 获取数据库最近的五条消息
        /// </summary>
        /// <param name="chatName"></param>
        /// <param name="v"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        private List<ChatMessage> GetRecentMessagesFromDatabase(int brokerId, int number = 0)
        {
            List<ChatMessage> messageList = new List<ChatMessage>();
            try
            {
                messageList = _dailyData.GetRecentMessagesByBrokerName(brokerId, number);
            }
            catch (Exception ex)
            {
                AppLog.WriteError("GetRecentMessagesFromDatabase异常" + ex.Message + ex.StackTrace);
            }

            return messageList; // 确保在所有情况下都有返回值
        }

        public List<ChatMessage> ParseMessages(string input)
        {
            try
            {
                List<ChatMessage> messages = new List<ChatMessage>();


                string[] lines = input.Split(new[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
                ChatMessage currentMessage = null;

                bool isQuoteMessage = false;
                foreach (string line in lines)
                {
                    string trimmedLine = line.Trim();
                    // Check if the line starts with a sender and timestamp
                    if (IsSenderTimestampLine(line)) //判断是时间戳和发送人
                    {
                        // If there is an existing message, add it to the list
                        if (currentMessage != null)
                        {

                            currentMessage.ChatMessageInfo = currentMessage.ChatMessageInfo.TrimEnd('\r');

                            if (isQuoteMessage)
                            {
                                currentMessage.ChatMessageInfo += "(回复内容）";
                                isQuoteMessage = false;
                            }
                            messages.Add(currentMessage);
                        }

                        // Create a new message
                        currentMessage = new ChatMessage();
                        string[] parts = line.Split(new[] { ' ' }, 3);
                        if (parts.Length < 3)
                        {
                            continue;
                        }
                        string timestampPart = parts[2].TrimEnd('\r');  // 去掉 '\r'
                        currentMessage.BrokerName = parts[0];
                        // 假设 parts[0] 是用来查找的目标值
                        var targetReceiverExists = Receivers.Any(o => o.ChatId == parts[0]);


                        // 判断时间戳部分是否为正确的时间格式，并且第二部分为空时，设定为今天的日期
                        if (DateTime.TryParseExact(timestampPart, "HH:mm:ss", CultureInfo.InvariantCulture, DateTimeStyles.None, out _))
                        {
                            if (string.IsNullOrEmpty(parts[1]))
                            {
                                parts[1] = DateTime.Today.ToString("yyyy/M/d");
                            }
                        }
                        else if (parts[1] == "")
                        {
                            parts[1] = DateTime.Today.ToString("yyyy/M/d");
                        }
                        // 根据是否找到匹配项设置 currentMessage.Direction 的值
                        currentMessage.Direction = (short?)(targetReceiverExists ? 1 : 0);
                        string dateTimeStr = $"{parts[1]} {timestampPart}";
                        DateTime dateTime1;
                        if (DateTime.TryParseExact(dateTimeStr, "yyyy/M/d H:mm:ss", CultureInfo.InvariantCulture, DateTimeStyles.None, out dateTime1))
                        {
                            currentMessage.CreateTime = dateTime1;
                        }
                        else
                        {
                            AppLog.WriteError($"日期解析失败 '{dateTimeStr}' as DateTime.");
                            // 如果解析失败，可以进行相应的处理，比如记录日志或者设定一个默认时间
                            Console.WriteLine($"Failed to parse '{dateTimeStr}' as DateTime.");
                        }

                        currentMessage.ChatMessageInfo = string.Empty;
                    }
                    else  //是内容消息（记得区分 引用和非引用）
                    {
                        // 处理消息内容
                        if (currentMessage != null)
                        {


                            trimmedLine = line.TrimEnd('\r'); // 去掉行末的 '\r'
                            if (!string.IsNullOrEmpty(currentMessage.ChatMessageInfo))
                            {
                                currentMessage.ChatMessageInfo += "\r"; // 换行符
                            }

                            currentMessage.ChatMessageInfo += trimmedLine;

                            if (isQuoteMessage)
                            {
                                currentMessage.ChatMessageInfo += "\r";
                                currentMessage.QuoteMessage = trimmedLine;

                                ///找是否是引用消息？
                                int yinYongCount = 0;
                                if (SelectMessageInMessages(trimmedLine, messages))
                                {
                                    currentMessage.ChatMessageInfo += "\r\n";
                                    isQuoteMessage = true;
                                }
                                else
                                {
                                    isQuoteMessage = false;
                                    currentMessage.ChatMessageInfo += "【回复消息】（系统判断）：\r";
                                }

                            }

                            if ((trimmedLine.StartsWith("吴忠贤") || trimmedLine.StartsWith("钟长明") || trimmedLine.StartsWith("谷苏")))
                            {
                                currentMessage.IsQuote = true;  // 第一行是引用消息
                                isQuoteMessage = true;
                                currentMessage.ChatMessageInfo += "\r\n【引用消息】（系统判断）：\r";
                                // 设置引用消息格式
                            }

                        }
                        //// Append to the current message's content
                        //string trimline = line.Replace("\r", "");
                        //if (currentMessage != null)
                        //{
                        //    if (!string.IsNullOrEmpty(currentMessage.ChatMessageInfo))
                        //    {
                        //        currentMessage.ChatMessageInfo += trimline+="  ";
                        //    }
                        //    else
                        //    {
                        //        currentMessage.ChatMessageInfo += trimmedLine;
                        //        // Check if the first line of content indicates a quoted message
                        //        if (trimmedLine.StartsWith("钟长明") || trimmedLine.StartsWith("谷苏") || trimmedLine.StartsWith("吴忠贤"))
                        //        {
                        //            currentMessage.QuoteMessage = "是引用消息";
                        //            currentMessage.ChatMessageInfo += "(引用消息）——";
                        //        }
                        //    }
                        //}
                    }
                }

                // Add the last message if any
                if (currentMessage != null)
                {
                    if (isQuoteMessage)
                    {
                        isQuoteMessage = false;
                    }
                    currentMessage.ChatMessageInfo = currentMessage.ChatMessageInfo.TrimEnd('\r');
                    messages.Add(currentMessage);
                }
                return messages;
            }
            catch (Exception ex)
            {
                AppLog.WriteError("解析消息list异常" + ex.Message);
            }
            return null;
        }

        /// <summary>
        /// 判断是否是引用消息
        /// </summary>
        /// <param name="trimmedLine"></param>
        /// <param name="messages"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        private bool SelectMessageInMessages(string trimmedLine, List<ChatMessage> messages)
        {
            try
            {
                if (messages.Where(o => o.ChatMessageInfo.Contains(trimmedLine)).Count() > 1)
                {
                    AppLog.WriteInfo("是引用消息，回复-" + messages[0].ChatMessageInfo + "和引用" + messages[0].QuoteMessage);
                    return true;
                }
                else
                {
                    return false;
                }
            }catch(Exception ex)
            {
                AppLog.WriteInfo("SelectMessageInMessages异常"+ex.Message+ex.StackTrace);
                return false;
            }
           
        }

        bool IsValidDateTime(string dateTimeString)
        {
            return DateTime.TryParseExact(dateTimeString, "yyyy/M/d H:mm:ss",
                                          System.Globalization.CultureInfo.InvariantCulture,
                                          System.Globalization.DateTimeStyles.None, out _);
        }
        //private static bool IsSenderTimestampLine(string line)
        //{

        //    string[] parts = line.Split(' ');
        //    if (parts.Length >= 3)
        //    {
        //        DateTime temp;
        //        bool result = DateTime.TryParseExact($"{parts[1]} {parts[2]}".TrimEnd('\r'), "yyyy/M/d HH:mm:ss", CultureInfo.InvariantCulture, DateTimeStyles.None, out temp);
        //        return result;
        //    }
        //    return false;
        //}
        private bool IsSenderTimestampLine(string line)
        {
            try
            {
                string[] parts = line.Split(new char[] { ' ', '\r' }, StringSplitOptions.RemoveEmptyEntries);


                // Check if line has at least 3 parts for the first format
                if (parts.Length >= 3)
                {
                    // Format: 吴忠贤 2024/6/25 13:00:38
                    string dateString = $"{parts[1]} {parts[2]}";
                    //bool isTime = DateTime.TryParse(dateString, out _);

                    //return isTime;

                    //bool isExactMatch = DateTime.TryParseExact(dateString, "yyyy/M/d H:mm:ss", CultureInfo.InvariantCulture, DateTimeStyles.None, out _);
                    bool isExactMatch = DateTime.TryParseExact(dateString, "yyyy/M/d H:mm:ss", CultureInfo.InvariantCulture, DateTimeStyles.None, out _);
                    return isExactMatch;
                }
                else if (parts.Length == 2)
                {
                    // Format: 吴忠贤  9:13:21 (Assuming today's date for the missing date part)
                    string timePart = parts[1].Trim(); // Remove leading and trailing spaces

                    bool isTime = DateTime.TryParse(timePart, out _);
                    bool isBroker = IsChatName(parts[0].Trim());
                    bool result = isTime & isBroker;
                    return result;
                }

                //else if (parts.Length == 2)
                //{
                //    string dateString = $"{DateTime.Today.ToString("yyyy/M/d")} {parts[1].PadLeft(8, '0')}"; // Ensure time part has HH:mm:ss format
                //    bool temp1= DateTime.TryParseExact(dateString, "yyyy/M/d HH:mm:ss", CultureInfo.InvariantCulture, DateTimeStyles.None, out _);

                //    this.OrderLog+=$"特殊时间+{line}+返回+{temp1}"+"\r\n";
                //    return DateTime.TryParseExact(dateString, "yyyy/M/d HH:mm:ss", CultureInfo.InvariantCulture, DateTimeStyles.None, out _);
                //    //string dateString = $"{DateTime.Today.ToString("yyyy/M/d")} {parts[1]}";
                //    //return DateTime.TryParseExact(dateString, "yyyy/M/d HH:mm:ss", CultureInfo.InvariantCulture, DateTimeStyles.None, out _);
                //}

                return false;
            }catch(Exception ex)
            {
                AppLog.WriteError($"IsSenderTimestampLine异常，{ex.StackTrace},{ex.Message}");
                return false;
            }
           
        }

        private bool IsChatName(string chatname)
        {
            try
            {
                if (BrokerList.Contains(chatname) || chatname == "吴忠贤")
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (Exception ex)
            {
                AppLog.WriteError($"IsChatName异常,{ex.StackTrace},{ex.Message}");
                return false;
            }

        }

        private int GetColorRGB(Point p)
        {
            IntPtr hdc = Helper.WindowHelper.GetDC(new IntPtr(0));//取到设备场景(0就是全屏的设备场景) 
            int color = Helper.WindowHelper.GetPixel(hdc, p);//取指定点颜色 
            Helper.WindowHelper.ReleaseDC(IntPtr.Zero, hdc);
            return color;

        }
        #endregion

        #region 强制关闭和重启
        private GlobalHotKeyManager _hotKeyManager;
        private void RegisterHotKey()
        {
            _hotKeyManager = new GlobalHotKeyManager();
            _hotKeyManager.OnHotKeyPressed += StopTimer;
            // 注册热键
            _hotKeyManager.RegisterGlobalHotKey(PrismApplication.Current.MainWindow);
        }

        private void StopTimer()
        {
            try
            {
                if (timer != null && timer.Enabled)
                {
                    Growl.SuccessGlobal("成功关闭扫描QTRADE");
                    timer.Stop();
                    AppLog.WriteInfo("成功关闭扫描QTRADE");
                }
                else
                {
                    Growl.SuccessGlobal("成功开启QTRADE服务");
                    timer?.Start();
                    AppLog.WriteInfo("成功开启扫描QTRADE~");
                }
            }
            catch(Exception ex)
            {
                AppLog.WriteError($"StopTimer异常,{ex.StackTrace},{ex.Message}");
            }
          
        }

        #endregion

        #region 对接刘-服务端（http接口）

        public const string ChannelId = "f09639756a47415fb4fbf6d31febbad4";

        private object lilyObj = new object();
        /// <summary>
        /// 0代表用户消息，1代表中介消息
        /// </summary>
        /// <param name="i"></param>
        /// 
        private readonly SemaphoreSlim semaphoreSlim = new SemaphoreSlim(1, 1);

        private async Task SaveMessageToLily(short i, ChatMessage chatMessage)
        {
            try
            {
                // Wait asynchronously to enter the semaphore
                await semaphoreSlim.WaitAsync();
                AppLog.WriteInfo($"记录SaveMessageToLily数据为{chatMessage.ToString()},方向{i}");
                if (i == 0)
                {
                    using (var client = new HttpClient())
                    {
                        var data = new
                        {
                            chatId = chatMessage.ChatId,
                            message = chatMessage.ChatMessageInfo,
                            brokerId = chatMessage.BrokerId,
                            channelId = ChannelId,
                            direction = 0,
                            tradeId = chatMessage.TradeId ?? null,
                            createTime = chatMessage.CreateTime
                        };

                        var request = new HttpRequestMessage(HttpMethod.Post, $"{DataHelper.BaseConfig.HttpUrl}/chatMessage/pro/send");
                        request.Headers.Add("Authorization", UserHelper.Token);

                        var json = JsonConvert.SerializeObject(data);
                        var content = new StringContent(json, Encoding.UTF8, "application/json");
                        request.Content = content;

                        var response = await client.SendAsync(request);
                        response.EnsureSuccessStatusCode();

                        string brokerName = Receivers.Where(o => o.Brokerid == chatMessage.BrokerId).FirstOrDefault()?.ChatId;
                        if(string.IsNullOrEmpty(brokerName))
                        {
                            AppLog.WriteError($"brokername为空！异常，brokerId为{chatMessage.BrokerId}");
                            return;
                        }
                        if (brokerName != null && !string.IsNullOrEmpty(chatMessage.ChatMessageInfo))
                        {
                            // 使用 ConcurrentBag 代替 List
                            var messages = OrderChatMessageDictionary.GetOrAdd(brokerName, new ConcurrentBag<string>());

                            // 不需要显式锁定，ConcurrentBag 是线程安全的
                            messages.Add(chatMessage.ChatMessageInfo);
                        }


                        AppLog.WriteInfo($"捕获到下单消息,时间{data.createTime},中介：{data.brokerId},消息：{data.message},发送人ID:{data.chatId}");
                        PrismApplication.Current.Dispatcher.Invoke(() =>
                        {
                            ChatMessageLog += "发给lily端-用户下单  " + $"中介：{data.brokerId}" +
                            chatMessage.ChatMessageInfo + DateTime.Now + "  \r\n";
                        });
                    }
                }
                else
                {
                    using (var client = new HttpClient())
                    {
                        var data = new
                        {
                            message = chatMessage.ChatMessageInfo,
                            brokerId = chatMessage.BrokerId,
                            channelId = ChannelId,
                            direction = 1,
                            createTime = (DateTime?)null,
                        };

                        var request = new HttpRequestMessage(HttpMethod.Post, $"{DataHelper.BaseConfig.HttpUrl}/chatMessage/pro/send");
                        request.Headers.Add("Authorization", UserHelper.Token);

                        var json = JsonConvert.SerializeObject(data);
                        var content = new StringContent(json, Encoding.UTF8, "application/json");
                        request.Content = content;

                        AppLog.WriteInfo($"捕获到中介消息,时间{data.createTime},中介：{data.brokerId},消息：{data.message},发送人ID:{"空"}");

                        var response = await client.SendAsync(request);
                        response.EnsureSuccessStatusCode();

                        PrismApplication.Current.Dispatcher.Invoke(() =>
                        {
                            ChatMessageLog += "发给lily端-中介回复  " + chatMessage.ChatMessageInfo + DateTime.Now + "  \r\n";
                        });
                    }
                }
            }
            catch (Exception ex)
            {
                AppLog.WriteError("SaveMessageToLily异常" + ex.Message + ex.StackTrace);
            }
            finally
            {
                // Release the semaphore
                semaphoreSlim.Release();
            }
        }

        //private async void SaveMessageToLily(short i, ChatMessage chatMessage)
        //{
        //    try
        //    {
        //        lock(lilyObj)
        //        {
        //            if (i == 0)
        //            {
        //                using (var client = new HttpClient())
        //                {
        //                    // 创建一个包含用户ID的匿名对象
        //                    var data = new
        //                    {
        //                        chatId = chatMessage.ChatId,
        //                        message = chatMessage.ChatMessageInfo,
        //                        brokerId = chatMessage.BrokerId,
        //                        channelId = ChannelId,
        //                        direction = 0,
        //                        tradeId = chatMessage.TradeId ?? null,
        //                        createTime = chatMessage.CreateTime
        //                    };

        //                    var request = new HttpRequestMessage(HttpMethod.Post, $"{DataHelper.BaseConfig.HttpUrl}/chatMessage/pro/send");

        //                    request.Headers.Add("Authorization", UserHelper.Token);
        //                    var json = JsonConvert.SerializeObject(data);
        //                    var content = new StringContent(json, Encoding.UTF8, "application/json");

        //                    request.Content = content;

        //                    var response = await client.SendAsync(request);
        //                    //var tmp = response.Content.ReadAsStringAsync().Result;
        //                    response.EnsureSuccessStatusCode();

        //                    string brokerName = Receivers.Where(o => o.Brokerid == chatMessage.BrokerId).FirstOrDefault().ChatId;
        //                    // 确保消息能正确地添加到字典中
        //                    if (brokerName != null && !String.IsNullOrEmpty(chatMessage.ChatMessageInfo))
        //                    {
        //                        // 使用 GetOrAdd 方法获取或添加新的列表
        //                        List<string> messages = OrderChatMessageDictionary.GetOrAdd(brokerName, new List<string>());

        //                        // 向列表中添加消息
        //                        lock (messages)
        //                        {
        //                            messages.Add(chatMessage.ChatMessageInfo);
        //                        }
        //                    }

        //                    AppLog.WriteFatal($"捕获到下单消息,时间{data.createTime},中介：{data.brokerId},消息：{data.message},发送人ID:{data.chatId}");
        //                    PrismApplication.Current.Dispatcher.Invoke(() =>
        //                    {
        //                        ChatMessageLog += "发给lily端-用户下单  " + $"中介：{data.brokerId}" +
        //                        chatMessage.ChatMessageInfo + DateTime.Now + "  \r\n";
        //                    });

        //                }
        //            }
        //            else
        //            {
        //                using (var client = new HttpClient())
        //                {
        //                    // 创建一个包含用户ID的匿名对象，中介端没有 chatId 和 tradeId
        //                    var data = new
        //                    {
        //                        message = chatMessage.ChatMessageInfo,
        //                        brokerId = chatMessage.BrokerId,
        //                        channelId = ChannelId,
        //                        direction = 1,
        //                        createTime = (DateTime?)null,
        //                    };

        //                    using (var request = new HttpRequestMessage(HttpMethod.Post, $"{DataHelper.BaseConfig.HttpUrl}/chatMessage/pro/send"))
        //                    {
        //                        request.Headers.Add("Authorization", UserHelper.Token);
        //                        var json = JsonConvert.SerializeObject(data);
        //                        var content = new StringContent(json, Encoding.UTF8, "application/json");
        //                        request.Content = content;

        //                        AppLog.WriteFatal($"捕获到中介消息,时间{data.createTime},中介：{data.brokerId},消息：{data.message},发送人ID:{"空"}");

        //                        using (var response = await client.SendAsync(request))
        //                        {
        //                            //var tmp = response.Content.ReadAsStringAsync().Result;
        //                            response.EnsureSuccessStatusCode();
        //                        }
        //                    }

        //                    PrismApplication.Current.Dispatcher.Invoke(() =>
        //                    {
        //                        ChatMessageLog += "发给lily端-中介回复  " + chatMessage.ChatMessageInfo + DateTime.Now + "  \r\n";
        //                    });


        //                }

        //            }
        //        }

        //    }
        //    catch (Exception ex)
        //    {
        //        AppLog.WriteError("SaveMessageToLily异常" + ex.Message + ex.StackTrace);
        //    }

        //}
        #endregion


        #region 发送给客户端方法

        public void SendQTradeNotOpen()
        {
            var qsr = new QuanYiOrderServerResponseClass();
            qsr.DataType = QuanYiServerBaseClass.DataTypeEnum.QTradeNotOpen;
            serverWebSocketFromClient.SendResponseToClient(qsr);
        }
        #endregion
    }
}
